Esempio n. 1
0
        /// <summary>
        /// Test the successful local to remote playback and then remote to local
        /// with the media starting in the PLAY state on the local device. </summary>
        /// <exception cref="InterruptedException"> </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testCastMediaToRemoteDeviceAndBackFromPlaying() throws InterruptedException
        public virtual void testCastMediaToRemoteDeviceAndBackFromPlaying()
        {
            Log.v(TAG, "testCastMediaToRemoteDeviceAndBackFromPlaying");
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch(2);
            CountDownLatch countDownLatch = new CountDownLatch(2);

            solo.clickOnActionBarItem(R.id.media_router_menu_item);
            solo.clickInList(0);

            eventEmitter.once(EventType.DID_PAUSE, new EventListenerAnonymousInnerClassHelper3(this, countDownLatch));
            solo.waitForActivity(typeof(VideoCastControllerActivity));
            solo.sleep(10000);

            solo.assertCurrentActivity("VideoCastControllerActivity is displayed", typeof(VideoCastControllerActivity));

            IList <View> views = solo.CurrentViews;

            foreach (View v in views)
            {
                if (v is android.support.v7.app.MediaRouteButton)
                {
                    solo.clickOnView(v);
                }
            }
            solo.sleep(3000);

            solo.clickOnButton("Disconnect");
            solo.sleep(3000);

            countDownLatch.countDown();

            assertTrue("Timeout occurred.", countDownLatch.@await(3, TimeUnit.MINUTES));
        }
Esempio n. 2
0
        public void OnException(ITransport transport, Exception exception)
        {
            Tracer.Debug("Test: Received Exception from Transport: " + exception);
            exceptions.Add(exception);

            asyncErrorLatch.countDown();
        }
        public async Task CommitAsync(Enlistment enlistment)
        {
            using (await this.syncObject.LockAsync().Await())
            {
                try
                {
                    Tracer.Debug("Commit notification received for TX id: " + this.TransactionId);

                    if (this.TransactionId != null)
                    {
                        // Now notify the broker that a new XA'ish transaction has completed.
                        TransactionInfo info = new TransactionInfo();
                        info.ConnectionId  = this.connection.ConnectionId;
                        info.TransactionId = this.TransactionId;
                        info.Type          = (int)TransactionType.CommitTwoPhase;

                        await this.connection.CheckConnectedAsync().Await();

                        await this.connection.SyncRequestAsync(info).Await();

                        Tracer.Debug("Transaction Commit Done TX id: " + this.TransactionId);

                        RecoveryLogger.LogRecovered(this.TransactionId as XATransactionId);

                        // if server responds that nothing needs to be done, then reply done.
                        enlistment.Done();

                        AfterCommit();
                    }
                }
                catch (Exception ex)
                {
                    Tracer.DebugFormat("Transaction[{0}] Commit failed with error: {1}",
                                       this.TransactionId, ex.Message);
                    try
                    {
                        this.connection.OnAsyncException(ex);
                    }
                    catch (Exception error)
                    {
                        Tracer.Error(error.ToString());
                    }
                }
                finally
                {
                    this.currentEnlistment = null;
                    this.TransactionId     = null;
                    this.netTxState        = TxState.None;

                    CountDownLatch latch = this.recoveryComplete;
                    if (latch != null)
                    {
                        latch.countDown();
                    }

                    this.dtcControlEvent.Set();
                }
            }
        }
        private void OnTestAsynchRedliversMessage(IMessage msg)
        {
            counter++;
            try
            {
                ITextMessage message = msg as ITextMessage;
                switch (counter)
                {
                case 1:
                    Tracer.Debug("Got first Message: " + message.Text);
                    Assert.AreEqual("First", message.Text);
                    Assert.IsFalse(message.NMSRedelivered);
                    break;

                case 2:
                    Tracer.Debug("Got Second Message: " + message.Text);
                    Assert.AreEqual("Second", message.Text);
                    Assert.IsFalse(message.NMSRedelivered);
                    throw new Exception("Ignore Me");

                case 3:
                    Tracer.Debug("Got Third Message: " + message.Text);
                    Assert.AreEqual("Second", message.Text);
                    Assert.IsTrue(message.NMSRedelivered);
                    doneLatch.countDown();
                    break;

                default:
                    errorMessage = "Got too many messages: " + counter;
                    Tracer.Debug(errorMessage);
                    doneLatch.countDown();
                    break;
                }
            }
            catch (Exception e)
            {
                if (e.Message.Equals("Ignore Me"))
                {
                    throw;
                }

                errorMessage = "Got exception: " + e.Message;
                Tracer.Warn("Exception on Message Receive: " + e.Message);
                doneLatch.countDown();
            }
        }
Esempio n. 5
0
        internal void TransportInterruptionProcessingComplete()
        {
            CountDownLatch cdl = this.transportInterruptionProcessingComplete;

            if (cdl != null)
            {
                cdl.countDown();
            }
        }
            public void consumer_Listener(IMessage message)
            {
                ActiveMQTextMessage m = message as ActiveMQTextMessage;

                Tracer.DebugFormat("Received Message: {0} delivery count = {1}", m.Text, m.RedeliveryCounter);
                Assert.AreEqual("1st", m.Text);
                Assert.AreEqual(receivedCount.Value, m.RedeliveryCounter);
                receivedCount.GetAndSet(receivedCount.Value + 1);
                done.countDown();
            }
Esempio n. 7
0
        public virtual void Test()
        {
            Directory   dir = NewDirectory();
            IndexWriter w   = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));

            IList <long?>    numbers = new List <long?>();
            IList <BytesRef> binary  = new List <BytesRef>();
            IList <BytesRef> sorted  = new List <BytesRef>();
            int numDocs = AtLeast(100);

            for (int i = 0; i < numDocs; i++)
            {
                Document d      = new Document();
                long     number = Random().NextLong();
                d.Add(new NumericDocValuesField("number", number));
                BytesRef bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random()));
                d.Add(new BinaryDocValuesField("bytes", bytes));
                binary.Add(bytes);
                bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random()));
                d.Add(new SortedDocValuesField("sorted", bytes));
                sorted.Add(bytes);
                w.AddDocument(d);
                numbers.Add(number);
            }

            w.ForceMerge(1);
            IndexReader r = w.Reader;

            w.Dispose();

            Assert.AreEqual(1, r.Leaves.Count);
            AtomicReader ar = (AtomicReader)r.Leaves[0].Reader;

            int numThreads = TestUtil.NextInt(Random(), 2, 5);
            IList <ThreadClass> threads     = new List <ThreadClass>();
            CountDownLatch      startingGun = new CountDownLatch(1);

            for (int t = 0; t < numThreads; t++)
            {
                Random      threadRandom = new Random(Random().Next());
                ThreadClass thread       = new ThreadAnonymousInnerClassHelper(this, numbers, binary, sorted, numDocs, ar, startingGun, threadRandom);
                thread.Start();
                threads.Add(thread);
            }

            startingGun.countDown();

            foreach (ThreadClass thread in threads)
            {
                thread.Join();
            }

            r.Dispose();
            dir.Dispose();
        }
Esempio n. 8
0
 public override void processEvent(Event @event)
 {
     if (@event.properties.containsKey(Event.SKIP_CUE_POINTS))
     {
         latch.countDown();
     }
     else
     {
         outerInstance.state = State.COMPLETED_CONTENT;
     }
 }
Esempio n. 9
0
        public virtual void Test()
        {
            Directory         dir = NewFSDirectory(CreateTempDir("livefieldupdates"));
            IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));

            IndexWriter w = new IndexWriter(dir, iwc);

            SearcherManager mgr = new SearcherManager(w, true, new SearcherFactoryAnonymousInnerClassHelper());

            const int missing = -1;

            LiveFieldValues <IndexSearcher, int?> rt = new LiveFieldValuesAnonymousInnerClassHelper(mgr, missing);

            int numThreads = TestUtil.NextInt(Random(), 2, 5);

            if (VERBOSE)
            {
                Console.WriteLine(numThreads + " threads");
            }

            CountDownLatch      startingGun = new CountDownLatch(1);
            IList <ThreadClass> threads     = new List <ThreadClass>();

            int iters   = AtLeast(1000);
            int idCount = TestUtil.NextInt(Random(), 100, 10000);

            double reopenChance = Random().NextDouble() * 0.01;
            double deleteChance = Random().NextDouble() * 0.25;
            double addChance    = Random().NextDouble() * 0.5;

            for (int t = 0; t < numThreads; t++)
            {
                int         threadID     = t;
                Random      threadRandom = new Random(Random().Next());
                ThreadClass thread       = new ThreadAnonymousInnerClassHelper(w, mgr, missing, rt, startingGun, iters, idCount, reopenChance, deleteChance, addChance, t, threadID, threadRandom);
                threads.Add(thread);
                thread.Start();
            }

            startingGun.countDown();

            foreach (ThreadClass thread in threads)
            {
                thread.Join();
            }
            mgr.MaybeRefresh();
            Assert.AreEqual(0, rt.Size());

            rt.Dispose();
            mgr.Dispose();
            w.Dispose();
            dir.Dispose();
        }
Esempio n. 10
0
        private void OnMessageThenRollback(IMessage message)
        {
            gotOneMessage.countDown();
            try
            {
                session.Rollback();
            }
            catch (Exception)
            {
            }

            throw new Exception("Test force a redelivery");
        }
        //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
        //ORIGINAL LINE: @Test public void testCloseableScheduleWithFixedDelay() throws InterruptedException
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void testCloseableScheduleWithFixedDelay()
        {
            CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService);

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(QTY);
            CountDownLatch latch = new CountDownLatch(QTY);
            service.scheduleWithFixedDelay(() =>
                    {
                        latch.countDown();
                    }, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS);

            Assert.assertTrue(latch.@await((QTY * 2) * DELAY_MS, TimeUnit.MILLISECONDS));
        }
        public async Task InDoubtAsync(Enlistment enlistment)
        {
            using (await syncObject.LockAsync().Await())
            {
                try
                {
                    Tracer.Debug("In Doubt notification received for TX id: " + this.TransactionId);

                    await BeforeEndAsync().Await();

                    // Now notify the broker that Rollback should be performed.
                    TransactionInfo info = new TransactionInfo();
                    info.ConnectionId  = this.connection.ConnectionId;
                    info.TransactionId = this.TransactionId;
                    info.Type          = (int)TransactionType.End;

                    await this.connection.CheckConnectedAsync().Await();

                    await this.connection.SyncRequestAsync((TransactionInfo)info.Clone()).Await();

                    info.Type = (int)TransactionType.Rollback;
                    await this.connection.CheckConnectedAsync().Await();

                    await this.connection.SyncRequestAsync(info).Await();

                    Tracer.Debug("InDoubt Transaction Rollback Done TX id: " + this.TransactionId);

                    RecoveryLogger.LogRecovered(this.TransactionId as XATransactionId);

                    // if server responds that nothing needs to be done, then reply done.
                    enlistment.Done();

                    AfterRollback();
                }
                finally
                {
                    this.currentEnlistment = null;
                    this.TransactionId     = null;
                    this.netTxState        = TxState.None;

                    CountDownLatch latch = this.recoveryComplete;
                    if (latch != null)
                    {
                        latch.countDown();
                    }

                    this.dtcControlEvent.Set();
                }
            }
        }
        public virtual void TestStressDeleteQueue()
        {
            DocumentsWriterDeleteQueue queue        = new DocumentsWriterDeleteQueue();
            HashSet <Term>             uniqueValues = new HashSet <Term>();
            int size = 10000 + Random().Next(500) * RANDOM_MULTIPLIER;

            int?[] ids = new int?[size];
            for (int i = 0; i < ids.Length; i++)
            {
                ids[i] = Random().Next();
                uniqueValues.Add(new Term("id", ids[i].ToString()));
            }
            CountDownLatch latch      = new CountDownLatch(1);
            AtomicInteger  index      = new AtomicInteger(0);
            int            numThreads = 2 + Random().Next(5);

            UpdateThread[] threads = new UpdateThread[numThreads];
            for (int i = 0; i < threads.Length; i++)
            {
                threads[i] = new UpdateThread(queue, index, ids, latch);
                threads[i].Start();
            }
            latch.countDown();
            for (int i = 0; i < threads.Length; i++)
            {
                threads[i].Join();
            }

            foreach (UpdateThread updateThread in threads)
            {
                DeleteSlice slice = updateThread.Slice;
                queue.UpdateSlice(slice);
                BufferedUpdates deletes = updateThread.Deletes;
                slice.Apply(deletes, BufferedUpdates.MAX_INT);
                assertEquals(uniqueValues, new HashSet <Term>(deletes.Terms.Keys));
            }
            queue.TryApplyGlobalSlice();
            HashSet <Term> frozenSet = new HashSet <Term>();

            foreach (Term t in queue.FreezeGlobalBuffer(null).TermsIterable())
            {
                BytesRef bytesRef = new BytesRef();
                bytesRef.CopyBytes(t.Bytes);
                frozenSet.Add(new Term(t.Field, bytesRef));
            }
            Assert.AreEqual(0, queue.NumGlobalTermDeletes(), "num deletes must be 0 after freeze");
            Assert.AreEqual(uniqueValues.Count, frozenSet.Count);
            assertEquals(uniqueValues, frozenSet);
        }
Esempio n. 14
0
 public override void Start()
 {
     base.Start();
     if (firstStart.CompareAndSet(true, false))
     {
         try
         {
             next.Oneway(wireFormat.PreferredWireFormatInfo);
         }
         finally
         {
             wireInfoSentDownLatch.countDown();
         }
     }
 }
 public override void UpdateDocument(Term term, IEnumerable <IndexableField> doc, Analyzer analyzer)
 {
     base.UpdateDocument(term, doc, analyzer);
     try
     {
         if (WaitAfterUpdate)
         {
             Signal.countDown();
             Latch.@await();
         }
     }
     catch (ThreadInterruptedException e)
     {
         throw new ThreadInterruptedException(e);
     }
 }
Esempio n. 16
0
 public override IndexSearcher NewSearcher(IndexReader r)
 {
     try
     {
         if (TriedReopen.Get())
         {
             AwaitEnterWarm.countDown();
             AwaitClose.@await();
         }
     }
     catch (ThreadInterruptedException e)
     {
         //
     }
     return(new IndexSearcher(r, Es));
 }
        public void InDoubt(Enlistment enlistment)
        {
            try
            {
                dtcControlEvent.Reset();

                Tracer.Debug("In Doubt notification received for TX id: " + this.transactionId);

                BeforeEnd();

                // Now notify the broker that Rollback should be performed.
                TransactionInfo info = new TransactionInfo();
                info.ConnectionId  = this.connection.ConnectionId;
                info.TransactionId = this.transactionId;
                info.Type          = (int)TransactionType.End;

                this.connection.CheckConnected();
                this.connection.SyncRequest(info);

                info.Type = (int)TransactionType.Rollback;
                this.connection.CheckConnected();
                this.connection.SyncRequest(info);

                Tracer.Debug("InDoubt Transaction Rollback Done TX id: " + this.transactionId);

                RecoveryLogger.LogRecovered(this.transactionId as XATransactionId);

                // if server responds that nothing needs to be done, then reply done.
                enlistment.Done();

                AfterRollback();
            }
            finally
            {
                this.currentEnlistment = null;
                this.transactionId     = null;

                CountDownLatch latch = this.recoveryComplete;
                if (latch != null)
                {
                    latch.countDown();
                }

                this.dtcControlEvent.Set();
            }
        }
Esempio n. 18
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();
            }
        }
 public override void Run()
 {
     try
     {
         Signal.@await();
         Manager.MaybeRefresh();
         Writer.DeleteDocuments(new TermQuery(new Term("foo", "barista")));
         Manager.MaybeRefresh(); // kick off another reopen so we inc. the internal gen
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         Console.Write(e.StackTrace);
     }
     finally
     {
         Latch.countDown(); // let the add below finish
     }
 }
Esempio n. 20
0
        private void OnTracedReceiveMessage(IMessage message)
        {
            try
            {
                received.Add(((ITextMessage)message).Text);
            }
            catch (Exception e)
            {
                Assert.Fail("Error: " + e.Message);
            }

            if (++counter < maxDeliveries)
            {
                throw new Exception("force a redelivery");
            }

            // new blood
            counter = 0;
            gotTwoMessages.countDown();
        }
Esempio n. 21
0
        public virtual void TestMixedTypesDifferentThreads()
        {
            Directory   dir = NewDirectory();
            IndexWriter w   = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));

            CountDownLatch startingGun = new CountDownLatch(1);
            AtomicBoolean  hitExc      = new AtomicBoolean();

            ThreadClass[] threads = new ThreadClass[3];
            for (int i = 0; i < 3; i++)
            {
                Field field;
                if (i == 0)
                {
                    field = new SortedDocValuesField("foo", new BytesRef("hello"));
                }
                else if (i == 1)
                {
                    field = new NumericDocValuesField("foo", 0);
                }
                else
                {
                    field = new BinaryDocValuesField("foo", new BytesRef("bazz"));
                }
                Document doc = new Document();
                doc.Add(field);

                threads[i] = new ThreadAnonymousInnerClassHelper(this, w, startingGun, hitExc, doc);
                threads[i].Start();
            }

            startingGun.countDown();

            foreach (ThreadClass t in threads)
            {
                t.Join();
            }
            Assert.IsTrue(hitExc.Get());
            w.Dispose();
            dir.Dispose();
        }
Esempio n. 22
0
 public override void Run()
 {
     try
     {
         Document doc   = new Document();
         Field    field = NewTextField("field", "testData", Field.Store.YES);
         doc.Add(field);
         IndexWriter writer = new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
         IwConstructed.countDown();
         StartIndexing_Renamed.@await();
         writer.AddDocument(doc);
         writer.Dispose();
     }
     catch (Exception e)
     {
         Failed  = true;
         Failure = e;
         Console.WriteLine(e.StackTrace);
         return;
     }
 }
            protected override void DoMerge(MergePolicy.OneMerge merge)
            {
                try
                {
                    // Stall all incoming merges until we see
                    // maxMergeCount:
                    int count = RunningMergeCount.IncrementAndGet();
                    try
                    {
                        Assert.IsTrue(count <= MaxMergeCount, "count=" + count + " vs maxMergeCount=" + MaxMergeCount);
                        EnoughMergesWaiting.countDown();

                        // Stall this merge until we see exactly
                        // maxMergeCount merges waiting
                        while (true)
                        {
                            // wait for 10 milliseconds
                            if (EnoughMergesWaiting.@await(new TimeSpan(0, 0, 0, 0, 10)) || Failed.Get())
                            {
                                break;
                            }
                        }
                        // Then sleep a bit to give a chance for the bug
                        // (too many pending merges) to appear:
                        Thread.Sleep(20);
                        base.DoMerge(merge);
                    }
                    finally
                    {
                        RunningMergeCount.DecrementAndGet();
                    }
                }
                catch (Exception t)
                {
                    Failed.Set(true);
                    Writer.MergeFinish(merge);
                    throw new Exception(t.Message, t);
                }
            }
Esempio n. 24
0
        public virtual void TestHashCodeWithThreads()
        {
            AutomatonQuery[] queries = new AutomatonQuery[1000];
            for (int i = 0; i < queries.Length; i++)
            {
                queries[i] = new AutomatonQuery(new Term("bogus", "bogus"), AutomatonTestUtil.RandomAutomaton(Random()));
            }
            CountDownLatch startingGun = new CountDownLatch(1);
            int            numThreads  = TestUtil.NextInt(Random(), 2, 5);

            ThreadClass[] threads = new ThreadClass[numThreads];
            for (int threadID = 0; threadID < numThreads; threadID++)
            {
                ThreadClass thread = new ThreadAnonymousInnerClassHelper(this, queries, startingGun);
                threads[threadID] = thread;
                thread.Start();
            }
            startingGun.countDown();
            foreach (ThreadClass thread in threads)
            {
                thread.Join();
            }
        }
Esempio n. 25
0
        private void OnTestAsynchRecoverMessage(IMessage msg)
        {
            counter++;
            try
            {
                ITextMessage message = msg as ITextMessage;
                switch (counter)
                {
                case 1:
                    Tracer.Debug("Got first Message: " + message.Text);
                    Assert.AreEqual("First", message.Text);
                    Assert.IsFalse(message.NMSRedelivered);
                    message.Acknowledge();
                    break;

                case 2:
                    Tracer.Debug("Got Second Message: " + message.Text);
                    Assert.AreEqual("Second", message.Text);
                    Assert.IsFalse(message.NMSRedelivered);
                    session.Recover();
                    break;

                case 3:
                    Tracer.Debug("Got Third Message: " + message.Text);
                    Assert.AreEqual("Second", message.Text);
                    Assert.IsTrue(message.NMSRedelivered);
                    message.Acknowledge();
                    doneCountDownLatch.countDown();
                    break;

                default:
                    errorMessage = "Got too many messages: " + counter;
                    Tracer.Debug(errorMessage);
                    doneCountDownLatch.countDown();
                    break;
                }
            }
            catch (Exception e)
            {
                errorMessage = "Got exception: " + e.Message;
                Tracer.Warn("Exception on Message Receive: " + e.Message);
                doneCountDownLatch.countDown();
            }
        }
Esempio n. 26
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();
            }
        }
Esempio n. 27
0
 private void OnRedeliveredMessage(IMessage message)
 {
     gotMaxRedeliveries.countDown();
     throw new Exception("Test Forcing a Rollback");
 }
Esempio n. 28
0
 private void OnDlqMessage(IMessage message)
 {
     dlqMessages.Add(message);
     gotOneDlqMessage.countDown();
 }
 private void TaskThatCountsDown(object unused)
 {
     doneLatch.countDown();
 }
Esempio n. 30
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     readyCountDownLatch.countDown();
 }
            public override void Run()
            {
                DirectoryReader reader  = null;
                bool            success = false;

                try
                {
                    Random random = Random();
                    while (NumUpdates.GetAndDecrement() > 0)
                    {
                        double group = random.NextDouble();
                        Term   t;
                        if (group < 0.1)
                        {
                            t = new Term("updKey", "g0");
                        }
                        else if (group < 0.5)
                        {
                            t = new Term("updKey", "g1");
                        }
                        else if (group < 0.8)
                        {
                            t = new Term("updKey", "g2");
                        }
                        else
                        {
                            t = new Term("updKey", "g3");
                        }
                        //              System.out.println("[" + Thread.currentThread().getName() + "] numUpdates=" + numUpdates + " updateTerm=" + t);
                        if (random.NextBoolean()) // sometimes unset a value
                        {
                            //                System.err.println("[" + Thread.currentThread().getName() + "] t=" + t + ", f=" + f + ", updValue=UNSET");
                            Writer.UpdateBinaryDocValue(t, f, null);
                            Writer.UpdateNumericDocValue(t, Cf, null);
                        }
                        else
                        {
                            long updValue = random.Next();
                            //                System.err.println("[" + Thread.currentThread().getName() + "] t=" + t + ", f=" + f + ", updValue=" + updValue);
                            Writer.UpdateBinaryDocValue(t, f, TestBinaryDocValuesUpdates.ToBytes(updValue));
                            Writer.UpdateNumericDocValue(t, Cf, updValue * 2);
                        }

                        if (random.NextDouble() < 0.2)
                        {
                            // delete a random document
                            int doc = random.Next(NumDocs);
                            //                System.out.println("[" + Thread.currentThread().getName() + "] deleteDoc=doc" + doc);
                            Writer.DeleteDocuments(new Term("id", "doc" + doc));
                        }

                        if (random.NextDouble() < 0.05) // commit every 20 updates on average
                        {
                            //                  System.out.println("[" + Thread.currentThread().getName() + "] commit");
                            Writer.Commit();
                        }

                        if (random.NextDouble() < 0.1) // reopen NRT reader (apply updates), on average once every 10 updates
                        {
                            if (reader == null)
                            {
                                //                  System.out.println("[" + Thread.currentThread().getName() + "] open NRT");
                                reader = DirectoryReader.Open(Writer, true);
                            }
                            else
                            {
                                //                  System.out.println("[" + Thread.currentThread().getName() + "] reopen NRT");
                                DirectoryReader r2 = DirectoryReader.OpenIfChanged(reader, Writer, true);
                                if (r2 != null)
                                {
                                    reader.Dispose();
                                    reader = r2;
                                }
                            }
                        }
                    }
                    //            System.out.println("[" + Thread.currentThread().getName() + "] DONE");
                    success = true;
                }
                catch (IOException e)
                {
                    throw new Exception(e.Message, e);
                }
                finally
                {
                    if (reader != null)
                    {
                        try
                        {
                            reader.Dispose();
                        }
                        catch (IOException e)
                        {
                            if (success) // suppress this exception only if there was another exception
                            {
                                throw new Exception(e.Message, e);
                            }
                        }
                    }
                    Done.countDown();
                }
            }