/// <summary>
 /// Initializes a new instance of the <see cref="CachedMessageProducer"/> class.
 /// </summary>
 /// <param name="target">The target.</param>
 public CachedMessageProducer(IMessageProducer target)
 {
     this.target = target;
     this.msgDeliveryMode = target.DeliveryMode;
     this.priority = target.Priority;
     this.timeToLive = target.TimeToLive;
 }
		protected void SendMessage(IMessageProducer producer)
		{
			IMessage request = producer.CreateMessage();
			request.NMSCorrelationID = CORRELATION_ID;
			request.NMSType = "Test";
			producer.Send(request);
		}
Esempio n. 3
0
 public MQ()
 {
     producer = null;
     factory = null;
     connection = null;
     session = null;
 }
Esempio n. 4
0
        /// <summary>
        /// 创建中间件的接口
        /// </summary>
        public JmsBroker(String url,String queuename)
        {
            try
            {
                if (_factory == null)
                {
                    _factory = new ConnectionFactory(url);
                }

                if (_connection == null)
                {
                    _connection = _factory.CreateConnection();
                }
                if (_session == null)
                {
                    _session = _connection.CreateSession();
                }
                if (_prodcer == null)
                {
                    _prodcer = _session.CreateProducer(
                                 new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(queuename));
                }
            }
            catch(Exception msg)
            {
                log.Error(msg.Message);
            }
        }
Esempio n. 5
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;
        }
Esempio n. 6
0
        public void Dispose()
        {
            lock (this)
            {
                this.producer.Dispose();
                this.producer = null;

                if (this.isInitializedForSynchronous)
                {
                    this.responseBuffer.Clear();
                    this.responseBuffer = null;
                    this.responseConsumer.Dispose();
                    this.responseConsumer = null;
                }

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

                this.session.Dispose();
                this.session = null;
                this.messageFactory = null;
                this.connection = null;
                this.destination = null;
                this.asr.Close();
                this.asr = null;
            }
        }
        // Verbindung zum  Messaging-Server aktualisieren
        public void UpdateConnection()
        {
            try
            {
                // eventuell früher belegte Ressourcen freigeben
                CleanupResources();

                // Verbindung / Session / MessageProducer und -Consumer instanziieren
                if (connectionFactory == null)
                {
                    Console.WriteLine(brokerURL);
                    connectionFactory = new ConnectionFactory(brokerURL);
                }
                connection = connectionFactory.CreateConnection();
                session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                messageProducer = session.CreateProducer(new ActiveMQTopic(topicName));

                // Thread zum Empfang eingehender Nachrichten starten
                connection.Start();

                Console.WriteLine("Connection geändert, Broker-URL ist " + brokerURL);
            }
            catch (Exception e)
            {
                Console.WriteLine("*** EXCEPTION in updateConnection(): " + e.Message);
            }
        }
Esempio n. 8
0
 //Jms中间件
 public JmsBroker(JmsServerInfo serverinfo)
 {
     try
     {
         if (_factory == null)
         {
             Console.WriteLine("url:" + serverinfo.Url + ";" + serverinfo.QueueName);
             _factory = new ConnectionFactory("tcp://192.168.1.117:61616");
         }
         if (_connection == null)
         {
             _connection = _factory.CreateConnection();
         }
         if (_session == null)
         {
             _session = _connection.CreateSession(AcknowledgementMode.DupsOkAcknowledge);
         }
         if (_prodcer == null)
         {
             _prodcer = _session.CreateProducer(
                          new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(serverinfo.QueueName));
         }
     }
     catch (Exception msg)
     {
         log.Error(msg.Message);
     }
 }
Esempio n. 9
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;
            }
        }
        public void SetUp()
        {
            this.errorMessageProducer = A.Fake<IMessageProducer>();
            this.messageHandler = A.Fake<ActiveMqMessageHandler>();

            this.testee = new ActiveMqExceptionHandler(this.messageHandler);
        }
Esempio n. 11
0
 public Producer(IMessageProducer nmsProducer, SimulationParams simulationParams, Topic topic)
 {
     _nmsProducer = nmsProducer;
     _simulationParams = simulationParams;
     _topic = topic;
     MinSendTime = TimeSpan.MaxValue;
     MaxSendTime = TimeSpan.MinValue;
 }
 public CommandQueueWatcher(EnvironmentContext environment, IList<string> queueNames)
 {
     _messageProducer = new MessageProducer();
     _environment = environment;
     _tasks = new List<Task>();
     foreach (var queueName in queueNames ?? new List<string>())
         AddWatchedQueue(queueName);
 }
Esempio n. 13
0
		override public void SetUp()
        {
            base.SetUp();
			acknowledgementMode = AcknowledgementMode.Transactional;
            Drain();
            consumer = Session.CreateConsumer(Destination);
            producer = Session.CreateProducer(Destination);
        }
        public void AddProducer(IMessageProducer messageProducer)
        {
            messageProducer.Initialize(dataStoreManager);
            messageProducers.Add(messageProducer);

            var instance = messageProducer as IVariableFallbackHandler;
            if (instance != null)
                variableHandler.AddFallbackHandler(instance);
        }
Esempio n. 15
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);
 }
Esempio n. 16
0
 public TopicPublisher(string topicName, string brokerUri)
 {
     this.topicName = topicName;
     this.connectionFactory = new ConnectionFactory(brokerUri);
     this.connection = this.connectionFactory.CreateConnection();
     this.connection.Start();
     this.session = connection.CreateSession();
     ActiveMQTopic topic = new ActiveMQTopic(topicName);
     this.producer = this.session.CreateProducer(topic);
 }
Esempio n. 17
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, XMSC.DELIVERY_PERSISTENT);
     producer = session.CreateProducer(queue);
 }
Esempio n. 18
0
        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);
            }
        }
Esempio n. 19
0
        public PooledProducer(IMessageProducer producer, IDestination destination)
        {
            this.producer = producer;
            this.destination = destination;

            this.deliveryMode = producer.DeliveryMode;
            this.disableMessageID = producer.DisableMessageID;
            this.disableMessageTimestamp = producer.DisableMessageTimestamp;
            this.priority = producer.Priority;
            this.timeToLive = producer.TimeToLive;
        }
Esempio n. 20
0
    public UnparsedQueueManager(SystemConfig config)
    {
        Uri connecturi = new Uri(config.ACTIVEMQ_URI);
        IConnectionFactory factory = NMSConnectionFactory.CreateConnectionFactory(connecturi);
        connection = factory.CreateConnection();
        session = connection.CreateSession();

        connection.Start();
        IDestination destination = SessionUtil.GetDestination(session, config.UNPARSED_QUEUE);
        producer = session.CreateProducer(destination);
    }
Esempio n. 21
0
        public ActiveProducer(IConnection amqConnection, ISession amqSession, String amqQueueName, EasyNetQ.IBus rabbitBus)
        {
            _rabbitBus = rabbitBus;

            ActiveMQQueue topic = new ActiveMQQueue(amqQueueName);
            _amqProducer = amqSession.CreateProducer(topic);
            countOfMessages = 0;
            _timProducer = new Timer(2000);
            _timProducer.Elapsed += _timProducer_Elapsed;
            _timProducer.Enabled = true;
            log.Info("Producer Connected to Queue '" + amqQueueName + "'");
        }
Esempio n. 22
0
 public void Connect()
 {
     log.Debug("New physical producer created. About to connect.");
     factory = XmsUtilities.CreateConnectionFactory(address);
     connection = factory.CreateConnection();
     connection.ExceptionListener += OnError;
     session = connection.CreateSession(transactional, AcknowledgeMode.AutoAcknowledge);
     queue = session.CreateQueue(address.Queue);
     queue.SetIntProperty(XMSC.DELIVERY_MODE, XMSC.DELIVERY_PERSISTENT);
     producer = session.CreateProducer(queue);
     connected = true;
     log.Debug("New physical producer successfully connected.");
 }
Esempio n. 23
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);
        }
Esempio n. 24
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;
        }
Esempio n. 25
0
        public void Disconnect()
        {
            log.Debug("Physical producer about to be disconnected.");

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

            producer = null;
            queue = null;
            session = null;
            connection = null;

            log.Debug("Physical producer successfully disconnected.");
        }
Esempio n. 26
0
        public Server()
        {
            InitializeComponent();
            listBox1.DataSource = listener;

            //服务端
            String brokerUri = "stomp:tcp://" + host + ":" + port + "?transport.useLogging=true";
            factory = new NMSConnectionFactory(brokerUri);
            connection = factory.CreateConnection(user, password);
            connection.Start();
            session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            consumer = session.CreateConsumer(session.GetQueue(re_destination));
            producer = session.CreateProducer();
            listener.Add("Starting up Listener.");
            listener.Add("Waiting for messages...");
            t1 = new Thread(new ThreadStart(StartListener));
        }
        public void ProcessMessage(Apache.NMS.IMessage amqMessage, IMessageProducer errorMessageProducer)
        {
            try
            {
                var amqTextMessage = (ITextMessage)amqMessage;
                this.messageHandler.ProcessMessage(amqTextMessage);
            }
            catch (Exception e)
            {
                ActiveMQMessage errorMessage = (ActiveMQMessage)((ActiveMQMessage)amqMessage).Clone();
                errorMessage.ReadOnlyProperties = false;
                errorMessage.Properties["Bridge.Error.Message"] = e.ToString();
                errorMessage.Properties["Bridge.Error.OriginalDestination"] = amqMessage.NMSDestination.ToString();
                errorMessage.Properties["Bridge.Error.OriginalTimestamp"] = amqMessage.NMSTimestamp.ToString(CultureInfo.InvariantCulture);
                errorMessage.Properties["Bridge.Error.OriginalMessageId"] = amqMessage.NMSMessageId;

                errorMessageProducer.Send(errorMessage);
            }
        }
        public void SetUp()
        {
            A.Fake<IConnectionFactory>();
            _connection = A.Fake<IConnection>();
            _lazyConnection = new Lazy<IConnection>(() =>
            {
                _connection.Start();
                return _connection;
            });
            _session = A.Fake<ISession>();
            _producer = A.Fake<IMessageProducer>();
            _serializer = A.Fake<IMessageSerializer>();
            _destination = A.Fake<IDestination>();
            _message = A.Fake<IBytesMessage>();
            _messagePropertyProvider = A.Fake<IMessagePropertyProvider<IMessage>>();

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

            _publisher = new MessagePublisher<IMessage>(_lazyConnection, _destination, _serializer, _messagePropertyProvider, _testScheduler);
        }
Esempio n. 29
0
        public Client()
        {
            InitializeComponent();
            listBox2.DataSource = publisher;

            //客户端
            String brokerUri2 = "stomp:tcp://" + host + ":" + port;
            factory2 = new NMSConnectionFactory(brokerUri2);
            connection2 = factory2.CreateConnection(user, password);
            connection2.Start();
            session2 = connection2.CreateSession(AcknowledgementMode.AutoAcknowledge);
            dest2 = session2.GetQueue(se_destination);
            producer = session2.CreateProducer(dest2);
            consumer = session2.CreateConsumer(session2.GetQueue(re_destination));
            consumer.Listener += (lllll) =>
                {
                    publisher.Add(String.Format("Receive {0} CorrelationId {1}", listenercount++, lllll.NMSCorrelationID));
                };
            publisher.Add("Starting up Publisher.");
            publisher.Add("Sending  messages...");
            t2 = new Thread(new ThreadStart(StartPublisher));
        }
Esempio n. 30
0
 public NITValidator(IMessageProducer messageProducer, bool isFormatted)
 {
     this.messageProducer = messageProducer;
     this.isFormatted     = isFormatted;
 }
Esempio n. 31
0
 public NITValidator(bool isFormatted)
 {
     messageProducer  = new SimpleMessageProducer();
     this.isFormatted = isFormatted;
 }
Esempio n. 32
0
 public NITValidator()
 {
     messageProducer = new SimpleMessageProducer();
 }
Esempio n. 33
0
        public void TestInfiniteMaximumNumberOfRedeliveries()
        {
            using (Connection connection = (Connection)CreateConnection())
            {
                IRedeliveryPolicy policy = connection.RedeliveryPolicy;
                policy.InitialRedeliveryDelay = 100;
                policy.UseExponentialBackOff  = false;
                // let's set the maximum redeliveries to no maximum (ie. infinite)
                policy.MaximumRedeliveries = -1;

                connection.Start();
                ISession         session     = connection.CreateSession(AcknowledgementMode.Transactional);
                IDestination     destination = session.CreateTemporaryQueue();
                IMessageProducer producer    = session.CreateProducer(destination);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                // Send the messages
                producer.Send(session.CreateTextMessage("1st"));
                producer.Send(session.CreateTextMessage("2nd"));
                session.Commit();

                ITextMessage m;

                m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000));
                Assert.IsNotNull(m);
                Assert.AreEqual("1st", m.Text);
                session.Rollback();

                //we should be able to get the 1st message redelivered until a session.Commit is called
                m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000));
                Assert.IsNotNull(m);
                Assert.AreEqual("1st", m.Text);
                session.Rollback();

                m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000));
                Assert.IsNotNull(m);
                Assert.AreEqual("1st", m.Text);
                session.Rollback();

                m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000));
                Assert.IsNotNull(m);
                Assert.AreEqual("1st", m.Text);
                session.Rollback();

                m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000));
                Assert.IsNotNull(m);
                Assert.AreEqual("1st", m.Text);
                session.Rollback();

                m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000));
                Assert.IsNotNull(m);
                Assert.AreEqual("1st", m.Text);
                session.Commit();

                m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000));
                Assert.IsNotNull(m);
                Assert.AreEqual("2nd", m.Text);
                session.Commit();
            }
        }
Esempio n. 34
0
 public QueueLoggerProvider(IMessageProducer producer)
 {
     _Producer = producer;
 }
Esempio n. 35
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();
            }
        }
Esempio n. 36
0
        private static void RunWithOptions(CommandLineOpts opts)
        {
            ITrace logger = new Logger(Logger.ToLogLevel(opts.logLevel));

            Tracer.Trace = logger;

            string ip          = opts.host;
            Uri    providerUri = new Uri(ip);

            Console.WriteLine("scheme: {0}", providerUri.Scheme);

            IConnection conn = null;

            if (opts.topic == null && opts.queue == null)
            {
                Console.WriteLine("ERROR: Must specify a topic or queue destination");
                return;
            }
            try
            {
                NmsConnectionFactory factory = new NmsConnectionFactory(ip);
                if (opts.username != null)
                {
                    factory.UserName = opts.username;
                }
                if (opts.password != null)
                {
                    factory.Password = opts.password;
                }
                if (opts.clientId != null)
                {
                    factory.ClientId = opts.clientId;
                }

                if (opts.connTimeout != default)
                {
                    factory.SendTimeout = opts.connTimeout;
                }

                Console.WriteLine("Creating Connection...");
                conn = factory.CreateConnection();
                conn.ExceptionListener += (logger as Logger).LogException;
                Console.WriteLine("Created Connection.");
                Console.WriteLine("Version: {0}", conn.MetaData);
                Console.WriteLine("Creating Session...");
                ISession ses = conn.CreateSession();
                Console.WriteLine("Session Created.");

                conn.Start();
                IDestination dest = (opts.topic == null) ? (IDestination)ses.GetQueue(opts.queue) : (IDestination)ses.GetTopic(opts.topic);
                Console.WriteLine("Creating Message Producer for : {0}...", dest);
                IMessageProducer prod     = ses.CreateProducer(dest);
                IMessageConsumer consumer = ses.CreateConsumer(dest);
                Console.WriteLine("Created Message Producer.");
                prod.DeliveryMode = opts.mode == 0 ? MsgDeliveryMode.NonPersistent : MsgDeliveryMode.Persistent;
                prod.TimeToLive   = TimeSpan.FromSeconds(20);
                ITextMessage msg = prod.CreateTextMessage("Hello World!");

                Console.WriteLine("Sending Msg: {0}", msg.ToString());
                Console.WriteLine("Starting Connection...");
                conn.Start();
                Console.WriteLine("Connection Started: {0} Resquest Timeout: {1}", conn.IsStarted, conn.RequestTimeout);
                Console.WriteLine("Sending {0} Messages...", opts.NUM_MSG);
                for (int i = 0; i < opts.NUM_MSG; i++)
                {
                    Tracer.InfoFormat("Sending Msg {0}", i + 1);
                    // Text Msg Body
                    msg.Text = "Hello World! n: " + i;
                    prod.Send(msg);
                    msg.ClearBody();
                }

                IMessage rmsg = null;
                for (int i = 0; i < opts.NUM_MSG; i++)
                {
                    Tracer.InfoFormat("Waiting to receive message {0} from consumer.", i);
                    rmsg = consumer.Receive(TimeSpan.FromMilliseconds(opts.connTimeout));
                    if (rmsg == null)
                    {
                        Console.WriteLine("Failed to receive Message in {0}ms.", opts.connTimeout);
                    }
                    else
                    {
                        Console.WriteLine("Received Message with id {0} and contents {1}.", rmsg.NMSMessageId, rmsg.ToString());
                    }
                }
                if (conn.IsStarted)
                {
                    Console.WriteLine("Closing Connection...");
                    conn.Close();
                    Console.WriteLine("Connection Closed.");
                }
            }
            catch (NMSException ne)
            {
                Console.WriteLine("Caught NMSException : {0} \nStack: {1}", ne.Message, ne);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught unexpected exception : {0}", e);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Dispose();
                }
            }
        }
Esempio n. 37
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);
            }
        }
Esempio n. 38
0
        public void TestSendSessionClose()
        {
            ITextMessage firstMsgSend;
            ITextMessage secondMsgSend;

            using (IConnection connection1 = CreateConnection(TEST_CLIENT_ID))
            {
                connection1.Start();
                using (ISession session1 = connection1.CreateSession(AcknowledgementMode.Transactional))
                {
                    IDestination destination1 = SessionUtil.GetDestination(session1, DESTINATION_NAME);
                    using (IMessageConsumer consumer = session1.CreateConsumer(destination1))
                    {
                        // First connection session that sends one message, and the
                        // second message is implicitly rolled back as the session is
                        // disposed before Commit() can be called.
                        using (IConnection connection2 = CreateConnection(TEST_CLIENT_ID2))
                        {
                            connection2.Start();
                            using (ISession session2 = connection2.CreateSession(AcknowledgementMode.Transactional))
                            {
                                IDestination destination2 = SessionUtil.GetDestination(session2, DESTINATION_NAME);
                                using (IMessageProducer producer = session2.CreateProducer(destination2))
                                {
                                    producer.Persistent     = false;
                                    producer.RequestTimeout = receiveTimeout;
                                    firstMsgSend            = session2.CreateTextMessage("First Message");
                                    producer.Send(firstMsgSend);
                                    session2.Commit();

                                    ITextMessage rollbackMsg = session2.CreateTextMessage("I'm going to get rolled back.");
                                    producer.Send(rollbackMsg);
                                }
                            }
                        }

                        // Second connection session that will send one message.
                        using (IConnection connection2 = CreateConnection(TEST_CLIENT_ID2))
                        {
                            connection2.Start();
                            using (ISession session2 = connection2.CreateSession(AcknowledgementMode.Transactional))
                            {
                                IDestination destination2 = SessionUtil.GetDestination(session2, DESTINATION_NAME);
                                using (IMessageProducer producer = session2.CreateProducer(destination2))
                                {
                                    producer.Persistent     = false;
                                    producer.RequestTimeout = receiveTimeout;
                                    secondMsgSend           = session2.CreateTextMessage("Second Message");
                                    producer.Send(secondMsgSend);
                                    session2.Commit();
                                }
                            }
                        }

                        // Check the consumer to verify which messages were actually received.
                        IMessage message = consumer.Receive(receiveTimeout);
                        AssertTextMessageEqual(firstMsgSend, message, "First message does not match.");

                        message = consumer.Receive(receiveTimeout);
                        AssertTextMessageEqual(secondMsgSend, message, "Second message does not match.");

                        // validates that the rollback was not consumed
                        session1.Commit();
                    }
                }
            }
        }
Esempio n. 39
0
        private static void RunWithOptionsStructured(CommandLineOpts opts)
        {
            ITrace logger = new Logger(Logger.ToLogLevel(opts.logLevel));

            Tracer.Trace = logger;

            string ip          = opts.host;
            Uri    providerUri = new Uri(ip);

            Console.WriteLine("scheme: {0}", providerUri.Scheme);

            IConnection conn = null;

            if (opts.topic == null && opts.queue == null)
            {
                Console.WriteLine("ERROR: Must specify a topic or queue destination");
                return;
            }
            try
            {
                NmsConnectionFactory factory = new NmsConnectionFactory(ip);
                if (opts.username != null)
                {
                    factory.UserName = opts.username;
                }
                if (opts.password != null)
                {
                    factory.Password = opts.password;
                }
                if (opts.clientId != null)
                {
                    factory.ClientId = opts.clientId;
                }

                if (opts.connTimeout != default)
                {
                    factory.SendTimeout = opts.connTimeout;
                }

                Console.WriteLine("Creating Connection...");
                conn = factory.CreateConnection();
                conn.ExceptionListener += (logger as Logger).LogException;
                Console.WriteLine("Created Connection.");
                Console.WriteLine("Version: {0}", conn.MetaData);
                Console.WriteLine("Creating Session...");
                ISession ses = conn.CreateSession();
                Console.WriteLine("Session Created.");

                conn.Start();
                IDestination dest = (opts.topic == null) ? (IDestination)ses.GetQueue(opts.queue) : (IDestination)ses.GetTopic(opts.topic);
                Console.WriteLine("Creating Message Producer for : {0}...", dest);
                IMessageProducer prod     = ses.CreateProducer(dest);
                IMessageConsumer consumer = ses.CreateConsumer(dest);
                Console.WriteLine("Created Message Producer.");
                prod.DeliveryMode = opts.mode == 0 ? MsgDeliveryMode.NonPersistent : MsgDeliveryMode.Persistent;
                prod.TimeToLive   = TimeSpan.FromSeconds(20);
                IMapMessage    mapMsg    = prod.CreateMapMessage();
                IStreamMessage streamMsg = prod.CreateStreamMessage();

                Console.WriteLine("Starting Connection...");
                conn.Start();
                Console.WriteLine("Connection Started: {0} Resquest Timeout: {1}", conn.IsStarted, conn.RequestTimeout);
                Tracer.InfoFormat("Sending MapMsg");
                // Map Msg Body
                mapMsg.Body.SetString("mykey", "Hello World!");
                mapMsg.Body.SetBytes("myBytesKey", new byte[] { 0x6d, 0x61, 0x70 });
                Console.WriteLine("Sending Msg: {0}", mapMsg.ToString());
                prod.Send(mapMsg);
                mapMsg.ClearBody();

                // Stream  Msg Body
                streamMsg.WriteBytes(new byte[] { 0x53, 0x74, 0x72 });
                streamMsg.WriteInt64(1354684651565648484L);
                streamMsg.WriteObject("bar");
                streamMsg.Properties["foobar"] = 42 + "";
                Console.WriteLine("Sending Msg: {0}", streamMsg.ToString());
                prod.Send(streamMsg);
                streamMsg.ClearBody();

                IMessage rmsg = null;
                for (int i = 0; i < 2; i++)
                {
                    Tracer.InfoFormat("Waiting to receive message {0} from consumer.", i);
                    rmsg = consumer.Receive(TimeSpan.FromMilliseconds(opts.connTimeout));
                    if (rmsg == null)
                    {
                        Console.WriteLine("Failed to receive Message in {0}ms.", opts.connTimeout);
                    }
                    else
                    {
                        Console.WriteLine("Received Message with id {0} and contents {1}.", rmsg.NMSMessageId, rmsg.ToString());
                        foreach (string key in rmsg.Properties.Keys)
                        {
                            Console.WriteLine("Message contains Property[{0}] = {1}", key, rmsg.Properties[key].ToString());
                        }
                    }
                }
                if (conn.IsStarted)
                {
                    Console.WriteLine("Closing Connection...");
                    conn.Close();
                    Console.WriteLine("Connection Closed.");
                }
            }
            catch (NMSException ne)
            {
                Console.WriteLine("Caught NMSException : {0} \nStack: {1}", ne.Message, ne);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught unexpected exception : {0}", e);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Dispose();
                }
            }
        }
Esempio n. 40
0
 public CreateNewApplicationUserCommandHandler(IApplicationUserRepository applicationUserRepository, IMessageProducer messageProducer)
 {
     _applicationUserRepository = applicationUserRepository;
     _messageProducer           = messageProducer;
 }
Esempio n. 41
0
 public MessageProducerWrapper(IMessageProducer producer)
 {
     this.producer = producer;
 }
Esempio n. 42
0
        public void SendReceiveMessageProperties(MsgDeliveryMode deliveryMode)
        {
            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.DeliveryMode   = deliveryMode;
                            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(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
                            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");
                        }
                }
            }
        }
Esempio n. 43
0
 public TestMqTransporter(IMessageProducer messageProducer) : base(messageProducer)
 {
 }
Esempio n. 44
0
 public SlackService(IMessageProducer _mqp) : base(_mqp)
 {
 }
Esempio n. 45
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();
            }
        }
        //[Test]
        public virtual void TestSendReceiveStreamMessage(
            //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode, string testQueueRef)
        {
            using (IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = GetClearDestination(session, DestinationType.Queue, testQueueRef);
                    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");
                        }
                }
            }
        }
Esempio n. 47
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();
                                        }
                                }
                    }
        }
 public UploadServices(IEbConnectionFactory _dbf, IMessageProducer _msp, IMessageQueueClient _mqc) : base(_dbf, _msp, _mqc)
 {
 }
Esempio n. 49
0
 public CachedMessageProducer(IDestination destination, IMessageProducer producer)
 {
     Destination = destination;
     _producer   = producer;
 }
Esempio n. 50
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");
                        }
                }
            }
        }
Esempio n. 51
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://localhost: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("test", "test"))
                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://FOO.BAR");

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

                    // 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;
                            producer.RequestTimeout = receiveTimeout;

                            consumer.Listener += new MessageListener(OnMessage);

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

                            stopwatch.Start();
                            producer.Send(request);


                            // Wait for the message
                            semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true);

                            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.Substring(0, 50));
                            }
                            Console.WriteLine("Press enter to exit");
                            Console.ReadLine();
                        }
                }
        }
Esempio n. 52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MQEventStreamStorager"/> class.
 /// </summary>
 /// <param name="messageProducer">The message producer.</param>
 /// <param name="jsonSerializer">The json serializer.</param>
 /// <param name="eventFilter">The eventFilter.</param>
 public MQEventStreamStorager(IMessageProducer messageProducer, IJsonSerializer jsonSerializer, Func <IOperateEvent, EventBehaviorStorager, bool> eventFilter)
     : this(messageProducer, jsonSerializer, null, LoggerBuilder.Empty)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultMessageProducerProvider"/> class.
 /// </summary>
 /// <param name="jsonSerializer">The json serializer.</param>
 /// <param name="messageProducer">The message producer.</param>
 public DefaultMessageProducerProvider(IMessageProducer messageProducer, IJsonSerializer jsonSerializer)
 {
     this.messageProducer = messageProducer ?? EmptyMessageProducer.Empty;
     this.jsonSerializer  = jsonSerializer ?? Never.Serialization.SerializeEnvironment.JsonSerializer;
 }
Esempio n. 54
0
 public ConnectorBuilder WithProducer(IMessageProducer producer)
 {
     this.producers.Add(producer);
     return(this);
 }
Esempio n. 55
0
 public TituloEleitoralValidator(IMessageProducer messageProducer)
 {
     this.messageProducer = messageProducer;
 }
        public void SendReceiveForeignStreamMessageTest(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Topic);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            try
                            {
                                producer.DeliveryMode = deliveryMode;
                                StreamMessage request = new StreamMessage();
                                request.Properties[propertyName] = propertyValue;

                                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(request.Properties.Count, message.Properties.Count, "Invalid number of properties.");
                                Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");

                                // Check the body
                                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");

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

                                // use type safe APIs
                                Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName);
                            }
                            catch (NotSupportedException)
                            {
                            }
                        }
                }
            }
        }
Esempio n. 57
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MQEventStreamStorager"/> class.
 /// </summary>
 /// <param name="messageProducer">The message producer.</param>
 /// <param name="jsonSerializer">The json serializer.</param>
 /// <param name="loggerBuilder">The logger builder.</param>
 protected MQEventStreamStorager(IMessageProducer messageProducer, IJsonSerializer jsonSerializer, ILoggerBuilder loggerBuilder)
     : this(messageProducer, jsonSerializer, null, loggerBuilder)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultMessageProducerProvider"/> class.
 /// </summary>
 /// <param name="messageProducer">The message producer.</param>
 public DefaultMessageProducerProvider(IMessageProducer messageProducer)
     : this(messageProducer, Never.Serialization.SerializeEnvironment.JsonSerializer)
 {
 }
Esempio n. 59
0
        /// <summary>
        /// Creates the producer, potentially returning a cached instance.
        /// </summary>
        /// <returns>A message producer, potentially cached.</returns>
        public IMessageProducer CreateProducer()
        {
            if (shouldCacheProducers)
            {
                if (cachedUnspecifiedDestinationMessageProducer != null)
                {
                    #region Logging

                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug("Found cached MessageProducer for unspecified destination");
                    }

                    #endregion
                }
                else
                {
                    #region Logging

                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug("Creating cached MessageProducer for unspecified destination");
                    }

                    #endregion
                    cachedUnspecifiedDestinationMessageProducer = target.CreateProducer();

                }
                this.transactionOpen = true;
                return new CachedMessageProducer(cachedUnspecifiedDestinationMessageProducer);
            }
            else
            {
                return target.CreateProducer();
            }
        }
Esempio n. 60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MQEventStreamStorager"/> class.
 /// </summary>
 /// <param name="messageProducer">The message producer.</param>
 /// <param name="jsonSerializer">The json serializer.</param>
 public MQEventStreamStorager(IMessageProducer messageProducer, IJsonSerializer jsonSerializer)
     : this(messageProducer, jsonSerializer, null, LoggerBuilder.Empty)
 {
 }