Ejemplo n.º 1
0
        public void DoTestAsynchRecover()
        {
            session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge);

            IMessageConsumer consumer = session.CreateConsumer(destination);

            IMessageProducer producer = session.CreateProducer(destination);

            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
            producer.Send(session.CreateTextMessage("First"));
            producer.Send(session.CreateTextMessage("Second"));

            consumer.Listener += OnTestAsynchRecoverMessage;
            connection.Start();

            if (doneCountDownLatch.await(TimeSpan.FromSeconds(10)))
            {
                if (!String.IsNullOrEmpty(errorMessage))
                {
                    Assert.Fail(errorMessage);
                }
            }
            else
            {
                Assert.Fail("Timeout waiting for async message delivery to complete.");
            }
        }
Ejemplo n.º 2
0
            public override void Run()
            {
                bool success = false;

                try
                {
                    if (_latch != null)
                    {
                        _latch.await();
                    }
                    // see the part in checkRandomData where it replays the same text again
                    // to verify reproducability/reuse: hopefully this would catch thread hazards.
                    CheckRandomData(new Random((int)Seed), a, Iterations, MaxWordLength, UseCharFilter, Simple, OffsetsAreCorrect, Iw);
                    success = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception in Thread: " + e);
                    throw;
                }
                finally
                {
                    Failed = !success;
                }
            }
        public void TestAsyncDispatchExceptionRedelivers()
        {
            using (var context = CreateContext(TEST_CLIENT_ID))
            {
                IQueue queue = context.GetQueue(DestinationName);

                using (var producer = context.CreateProducer())
                {
                    producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                    producer.Send(queue, producer.CreateTextMessage("First"));
                    producer.Send(queue, producer.CreateTextMessage("Second"));
                }

                using (var consumer = context.CreateConsumer(queue))
                {
                    consumer.Listener += OnTestAsynchRedliversMessage;
                    context.Start();

                    if (doneLatch.await(TimeSpan.FromSeconds(10)))
                    {
                        if (!String.IsNullOrEmpty(errorMessage))
                        {
                            Assert.Fail(errorMessage);
                        }
                    }
                    else
                    {
                        Assert.Fail("Timeout waiting for async message delivery to complete.");
                    }
                }
            }
        }
Ejemplo n.º 4
0
        private static Task Wrap(CountDownLatch signal, CancellationToken cancelToken)
        {
            TaskCompletionSource <bool> completionSource = new TaskCompletionSource <bool>();

            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    // This is bad.
                    while (!signal.await(500, TimeUnit.MILLISECONDS))
                    {
                        if (cancelToken.IsCancellationRequested)
                        {
                            completionSource.SetCanceled();
                            return;
                        }
                    }
                    completionSource.SetResult(true);
                }
                catch (Exception e)
                {
                    completionSource.SetException(e);
                }
            });
            return(completionSource.Task);
        }
Ejemplo n.º 5
0
 protected override void OnCommand(ITransport sender, Command command)
 {
     if (command.IsWireFormatInfo)
     {
         WireFormatInfo info = (WireFormatInfo)command;
         try
         {
             if (!info.Valid)
             {
                 throw new IOException("Remote wire format magic is invalid");
             }
             wireInfoSentDownLatch.await(negotiateTimeout);
             wireFormat.RenegotiateWireFormat(info);
         }
         catch (Exception e)
         {
             OnException(this, e);
         }
         finally
         {
             readyCountDownLatch.countDown();
         }
     }
     this.commandHandler(sender, command);
 }
Ejemplo n.º 6
0
        public void TestQueueSessionListenerExceptionRetry()
        {
            connection.Start();

            ISession         session  = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            IQueue           queue    = session.CreateTemporaryQueue();
            IMessageProducer producer = CreateProducer(session, queue);
            IMessage         message  = CreateTextMessage(session, "1");

            producer.Send(message);
            message = CreateTextMessage(session, "2");
            producer.Send(message);

            IMessageConsumer consumer = session.CreateConsumer(queue);

            consumer.Listener += new MessageListener(OnTracedReceiveMessage);

            Assert.IsTrue(gotTwoMessages.await(TimeSpan.FromSeconds(20)), "got message before retry expiry");

            for (int i = 0; i < maxDeliveries; i++)
            {
                Assert.AreEqual("1", received[i], "got first redelivered: " + i);
            }
            for (int i = maxDeliveries; i < maxDeliveries * 2; i++)
            {
                Assert.AreEqual("2", received[i], "got first redelivered: " + i);
            }

            session.Close();
        }
Ejemplo n.º 7
0
 public void TestPerformance() {
    CountDownLatch simpleDateFormatGate = new CountDownLatch(CONCURRENCY);
    CountDownLatch simpleDateFormatFinisher = new CountDownLatch(CONCURRENCY);
    AtomicLong simpleDateFormatCount = new AtomicLong();
    for(int i = 0; i < CONCURRENCY; i++) {
       new ThRead(new SimpleDateFormatTask(simpleDateFormatFinisher, simpleDateFormatGate, simpleDateFormatCount, FORMAT)).start();
    }
    simpleDateFormatFinisher.await();
    CountDownLatch synchronizedGate = new CountDownLatch(CONCURRENCY);
    CountDownLatch synchronizedFinisher = new CountDownLatch(CONCURRENCY);
    AtomicLong synchronizedCount = new AtomicLong();
    SimpleDateFormat format = new SimpleDateFormat(FORMAT);
    for(int i = 0; i < CONCURRENCY; i++) {
       new ThRead(new SynchronizedTask(synchronizedFinisher, synchronizedGate, synchronizedCount, format)).start();
    }
    synchronizedFinisher.await();
    CountDownLatch formatterGate = new CountDownLatch(CONCURRENCY);
    CountDownLatch formatterFinisher = new CountDownLatch(CONCURRENCY);
    AtomicLong formatterCount = new AtomicLong();
    DateFormatter formatter = new DateFormatter(FORMAT, CONCURRENCY);
    for(int i = 0; i < CONCURRENCY; i++) {
       new ThRead(new FormatterTask(formatterFinisher, formatterGate, formatterCount, formatter)).start();
    }
    formatterFinisher.await();
    System.err.printf("pool: %s, new: %s, synchronized: %s", formatterCount.get(),  simpleDateFormatCount.get(), synchronizedCount.get());
    //assertTrue(formatterCount.get() < simpleDateFormatCount.get());
    //assertTrue(formatterCount.get() < synchronizedCount.get()); // Synchronized is faster?
 }
Ejemplo n.º 8
0
 public override void Oneway(Command command)
 {
     if (!readyCountDownLatch.await(negotiateTimeout))
     {
         throw new IOException("Wire format negotiation timeout: peer did not send his wire format.");
     }
     next.Oneway(command);
 }
Ejemplo n.º 9
0
        public void TestQueueSessionListenerExceptionDlq()
        {
            connection.Start();

            session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            IQueue           queue    = session.CreateTemporaryQueue();
            IMessageProducer producer = CreateProducer(session, queue);
            IMessage         message  = CreateTextMessage(session);

            producer.Send(message);

            IDestination dlqDestination = session.GetQueue("ActiveMQ.DLQ");

            connection.DeleteDestination(dlqDestination);
            IMessageConsumer dlqConsumer = session.CreateConsumer(dlqDestination);

            dlqConsumer.Listener += new MessageListener(OnDlqMessage);

            IMessageConsumer consumer = session.CreateConsumer(queue);

            consumer.Listener += new MessageListener(OnRedeliveredMessage);

            Assert.IsTrue(gotMaxRedeliveries.await(TimeSpan.FromSeconds(20)), "got message before retry expiry");

            // check DLQ
            Assert.IsTrue(gotOneDlqMessage.await(TimeSpan.FromSeconds(20)), "got dlq message");

            // check DLQ message cause is captured
            message = dlqMessages[0] as IMessage;
            Assert.IsNotNull(message, "dlq message captured");
            String cause = message.Properties.GetString("dlqDeliveryFailureCause");

            Assert.IsTrue(cause.Contains("JMSException"), "cause 'cause' exception is remembered");
            Assert.IsTrue(cause.Contains("Test"), "is correct exception");
            Assert.IsTrue(cause.Contains("RedeliveryPolicy"), "cause policy is remembered");

            session.Close();
        }
Ejemplo n.º 10
0
        private void WaitForTransportInterruptionProcessingToComplete()
        {
            CountDownLatch cdl = this.transportInterruptionProcessingComplete;

            if (cdl != null)
            {
                if (!closed && cdl.Remaining > 0)
                {
                    Tracer.Warn("dispatch paused, waiting for outstanding dispatch interruption " +
                                "processing (" + cdl.Remaining + ") to complete..");
                    cdl.await(TimeSpan.FromSeconds(10));
                }
            }
        }
Ejemplo n.º 11
0
        private void WaitForTransportInterruptionProcessingToComplete()
        {
            CountDownLatch cdl = this.transportInterruptionProcessingComplete;

            if (cdl != null)
            {
                if (!closed.Value && cdl.Remaining > 0)
                {
                    Tracer.WarnFormat("Connection[{0}]: Dispatch paused, waiting for outstanding dispatch interruption " +
                                      "processing (" + cdl.Remaining + ") to complete..", this.ConnectionId);
                    cdl.await(TimeSpan.FromSeconds(10));
                }

                SignalInterruptionProcessingComplete();
            }
        }
Ejemplo n.º 12
0
        public void TestAcknowledgeIndividualMessagesAsync()
        {
            using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password))
            {
                testAmqpPeer.Open();

                int msgCount = 6;
                for (int i = 0; i < msgCount; i++)
                {
                    testAmqpPeer.SendMessage("myQueue", "test" + i);
                }

                IConnection connection = EstablishConnection();
                connection.Start();
                ISession session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge);

                IQueue           queue    = session.GetQueue("myQueue");
                IMessageConsumer consumer = session.CreateConsumer(queue);

                CountDownLatch      latch    = new CountDownLatch(msgCount);
                List <ITextMessage> messages = new List <ITextMessage>();
                consumer.Listener += message =>
                {
                    messages.Add((ITextMessage)message);
                    latch.countDown();
                };

                Assert.True(latch.await(TimeSpan.FromMilliseconds(1000)), $"Should receive: {msgCount}, but received: {messages.Count}");

                // Acknowledge the messages in a random order and verify the individual dispositions have expected delivery state.
                Random random = new Random();
                for (int i = 0; i < msgCount; i++)
                {
                    var message = messages[random.Next(msgCount - i)];
                    messages.Remove(message);
                    message.Acknowledge();

                    Assert.That(() => testAmqpPeer.AcceptedMessages.Any(x => x.Body.ToString() == message.Text), Is.True.After(200, 50));
                    Assert.That(() => testAmqpPeer.AcceptedMessages.Count(), Is.EqualTo(i + 1).After(200, 50), "Wrong number of messages acknowledged.");
                }

                connection.Close();
            }
        }
Ejemplo n.º 13
0
        public void TestClientAcknowledgeMessagesAsync()
        {
            using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password))
            {
                testAmqpPeer.Open();

                int msgCount = 3;
                for (int i = 0; i < msgCount; i++)
                {
                    testAmqpPeer.SendMessage("myQueue", "test" + i);
                }

                IConnection connection = EstablishConnection();
                connection.Start();
                ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge);

                IQueue           queue    = session.GetQueue("myQueue");
                IMessageConsumer consumer = session.CreateConsumer(queue);

                CountDownLatch latch = new CountDownLatch(3);
                IMessage       lastReceivedMessage = null;
                consumer.Listener += message =>
                {
                    lastReceivedMessage = message;
                    latch.countDown();
                };

                latch.await(TimeSpan.FromMilliseconds(100));

                lastReceivedMessage.Acknowledge();

                Assert.That(() => testAmqpPeer.AcceptedMessages.Count(), Is.EqualTo(3).After(200, 50));

                connection.Close();
            }
        }
        public void TestAsyncDispatchExceptionRedelivers()
        {
            using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
            {
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IQueue queue = SessionUtil.GetDestination(session, DESTINATION_NAME) as IQueue;

                    using (IMessageProducer producer = session.CreateProducer(queue))
                    {
                        producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                        producer.Send(producer.CreateTextMessage("First"));
                        producer.Send(producer.CreateTextMessage("Second"));
                    }

                    using (IMessageConsumer consumer = session.CreateConsumer(queue))
                    {
                        consumer.Listener += OnTestAsynchRedliversMessage;

                        connection.Start();

                        if (doneLatch.await(TimeSpan.FromSeconds(10)))
                        {
                            if (!String.IsNullOrEmpty(errorMessage))
                            {
                                Assert.Fail(errorMessage);
                            }
                        }
                        else
                        {
                            Assert.Fail("Timeout waiting for async message delivery to complete.");
                        }
                    }
                }
            }
        }
Ejemplo n.º 15
0
 private bool LatchAwait(CountDownLatch latch, TimeSpan time)
 {
     return(latch.await(time));
 }
Ejemplo n.º 16
0
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: @Override public ResponseCommand waitResponse(long timeoutMillis) throws ThreadInterruptedException
 public virtual ResponseCommand waitResponse(long timeoutMillis)
 {
     countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
     return(responseCommand);
 }
Ejemplo n.º 17
0
        public void TestTemporaryTopicReplyTo()
        {
            const int      NUM_MSGS        = 100;
            const string   MSG_BODY        = "num : ";
            IDestination   replyTo         = GetDestination("temp1");
            long           repliedCount    = 0;
            long           lastRepliedId   = -1;
            string         errString       = null;
            CountDownLatch replierFinished = new CountDownLatch(NUM_MSGS);


            using (IConnection connection = GetConnection("c1"))
                using (IMessageConsumer receiver = GetConsumer("receiver"))
                    using (IMessageConsumer listener = GetConsumer("listener"))
                        using (IMessageProducer sender = GetProducer("sender"))
                            using (IMessageProducer replyer = GetProducer("replyer"))
                            {
                                try
                                {
                                    connection.ExceptionListener += DefaultExceptionListener;
                                    ITextMessage rmsg    = null;
                                    ITextMessage sendMsg = sender.CreateTextMessage();
                                    sendMsg.NMSReplyTo = replyTo;

                                    listener.Listener += (message) =>
                                    {
                                        if (errString == null)
                                        {
                                            repliedCount++;
                                            long msgId = ExtractMsgId(message.NMSMessageId);
                                            if (msgId != lastRepliedId + 1)
                                            {
                                                // Test failed release blocked thread for shutdown.
                                                errString = String.Format("Received msg {0} out of order expected {1}", msgId, lastRepliedId + 1);
                                                waiter.Set();
                                            }
                                            else
                                            {
                                                lastRepliedId = msgId;
                                                if (msgId == NUM_MSGS - 1)
                                                {
                                                    message.Acknowledge();
                                                    // test done signal complete.
                                                    waiter.Set();
                                                    return;
                                                }
                                                message.Acknowledge();
                                            }
                                        }
                                    };

                                    receiver.Listener += (message) =>
                                    {
                                        if (errString == null)
                                        {
                                            msgCount++;
                                            rmsg = message as ITextMessage;
                                            if (rmsg == null)
                                            {
                                                // test failure
                                                errString = string.Format(
                                                    "Received message, id = {2}, body of type {0}, expected {1}.",
                                                    message.GetType().Name,
                                                    typeof(ITextMessage).Name,
                                                    ExtractMsgId(message.NMSMessageId)
                                                    );
                                                waiter.Set();
                                                return;
                                            }
                                            IDestination replyDestination = message.NMSReplyTo;
                                            if (!replyDestination.Equals(replyTo))
                                            {
                                                // test failure
                                                errString = string.Format(
                                                    "Received message, id = {0}, with incorrect reply Destination. Expected : {1}, Actual : {2}.",
                                                    ExtractMsgId(message.NMSMessageId),
                                                    replyTo,
                                                    replyDestination
                                                    );
                                                waiter.Set();
                                                return;
                                            }
                                            else
                                            {
                                                ITextMessage reply = replyer.CreateTextMessage();
                                                reply.Text = "Received:" + rmsg.Text;
                                                try
                                                {
                                                    replyer.Send(reply);
                                                    replierFinished.countDown();
                                                }
                                                catch (NMSException nEx)
                                                {
                                                    Logger.Error("Failed to send message from replyer Cause : " + nEx);
                                                    throw nEx;
                                                }
                                            }
                                        }
                                    };

                                    connection.Start();

                                    for (int i = 0; i < NUM_MSGS; i++)
                                    {
                                        sendMsg.Text = MSG_BODY + i;
                                        sender.Send(sendMsg);
                                    }

                                    // allow for two seconds for each message to be sent and replied to.
                                    int timeout = 2000 * NUM_MSGS;
                                    if (!waiter.WaitOne(timeout))
                                    {
                                        Assert.Fail("Timed out waiting on message delivery to complete. Received {1} of {0}, Replied {2} of {0}, Last Replied Msg Id {3}.", NUM_MSGS, msgCount, repliedCount, lastRepliedId);
                                    }
                                    else if (errString != null)
                                    {
                                        Assert.Fail("Asynchronous failure occurred. Cause : {0}", errString);
                                    }
                                    else
                                    {
                                        Assert.IsTrue(replierFinished.await(TimeSpan.FromMilliseconds(timeout)), "Replier thread has not finished sending messages. Remaining {0}", replierFinished.Remaining);
                                        Assert.IsNull(asyncEx, "Received Exception Asynchronously. Cause : {0}", asyncEx);
                                        Assert.AreEqual(NUM_MSGS, msgCount, "Failed to receive all messages.");
                                        Assert.AreEqual(NUM_MSGS, repliedCount, "Failed to reply to all messages");
                                        Assert.AreEqual(NUM_MSGS - 1, lastRepliedId, "Failed to receive the final message");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    this.PrintTestFailureAndAssert(GetTestMethodName(), "Unexpected exception.", ex);
                                }
                            }
        }
Ejemplo n.º 18
0
 public bool Await()
 {
     return(done.await(TimeSpan.FromMilliseconds(5000)));
 }