public override void Run()
 {
     try
     {
         StartingGun.@await();
         for (int i = 0; i < 20; i++)
         {
             IList <KeyValuePair <BytesRef, TopDocs> > shuffled = new List <KeyValuePair <BytesRef, TopDocs> >(Answers.EntrySet());
             shuffled = CollectionsHelper.Shuffle(shuffled);
             foreach (KeyValuePair <BytesRef, TopDocs> ent in shuffled)
             {
                 TopDocs actual   = s.Search(new TermQuery(new Term("body", ent.Key)), 100);
                 TopDocs expected = ent.Value;
                 Assert.AreEqual(expected.TotalHits, actual.TotalHits);
                 Assert.AreEqual(expected.ScoreDocs.Length, actual.ScoreDocs.Length, "query=" + ent.Key.Utf8ToString());
                 for (int hit = 0; hit < expected.ScoreDocs.Length; hit++)
                 {
                     Assert.AreEqual(expected.ScoreDocs[hit].Doc, actual.ScoreDocs[hit].Doc);
                     // Floats really should be identical:
                     Assert.IsTrue(expected.ScoreDocs[hit].Score == actual.ScoreDocs[hit].Score);
                 }
             }
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message, e);
     }
 }
示例#2
0
 public override void Run()
 {
     try
     {
         StartingGun.@await();
         while (!(Postings.Count == 0))
         {
             StringBuilder text     = new StringBuilder();
             int           numTerms = ThreadRandom.Next(MaxTermsPerDoc);
             for (int i = 0; i < numTerms; i++)
             {
                 string token;
                 if (!Postings.TryDequeue(out token))
                 {
                     break;
                 }
                 text.Append(' ');
                 text.Append(token);
             }
             Field.StringValue = text.ToString();
             Iw.AddDocument(Document);
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message, e);
     }
 }
示例#3
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));
        }
 protected override async Task 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();
         }
     }
     await this.commandHandlerAsync(sender, command).Await();
 }
示例#5
0
 public override void Run()
 {
     StartingGun.@await();
     for (int i = 0; i < Queries.Length; i++)
     {
         Queries[i].GetHashCode();
     }
 }
            public override void Run()
            {
                try
                {
                    Latch.@await();
                }
                catch (ThreadInterruptedException e)
                {
                    Failed = e;
                    return;
                }
                DirectoryReader reader;

                while ((reader = Holder.Reader) != null)
                {
                    if (reader.TryIncRef())
                    {
                        try
                        {
                            bool current = reader.Current;
                            if (VERBOSE)
                            {
                                Console.WriteLine("Thread: " + Thread.CurrentThread + " Reader: " + reader + " isCurrent:" + current);
                            }

                            Assert.IsFalse(current);
                        }
                        catch (Exception e)
                        {
                            if (VERBOSE)
                            {
                                Console.WriteLine("FAILED Thread: " + Thread.CurrentThread + " Reader: " + reader + " isCurrent: false");
                            }
                            Failed      = e;
                            Holder.Stop = true;
                            return;
                        }
                        finally
                        {
                            try
                            {
                                reader.DecRef();
                            }
                            catch (IOException e)
                            {
                                if (Failed == null)
                                {
                                    Failed = e;
                                }
                            }
                        }
                        return;
                    }
                }
            }
示例#7
0
            public override void Run()
            {
                try
                {
                    //NumericDocValues ndv = ar.GetNumericDocValues("number");
                    FieldCache.Longs ndv = FieldCache.DEFAULT.GetLongs(Ar, "number", false);
                    //BinaryDocValues bdv = ar.GetBinaryDocValues("bytes");
                    BinaryDocValues bdv = FieldCache.DEFAULT.GetTerms(Ar, "bytes", false);
                    SortedDocValues sdv = FieldCache.DEFAULT.GetTermsIndex(Ar, "sorted");
                    StartingGun.@await();
                    int      iters    = AtLeast(1000);
                    BytesRef scratch  = new BytesRef();
                    BytesRef scratch2 = new BytesRef();
                    for (int iter = 0; iter < iters; iter++)
                    {
                        int docID = ThreadRandom.Next(NumDocs);
                        switch (ThreadRandom.Next(6))
                        {
                        case 0:
                            Assert.AreEqual((long)(sbyte)Numbers[docID], FieldCache.DEFAULT.GetBytes(Ar, "number", false).Get(docID));
                            break;

                        case 1:
                            Assert.AreEqual((long)(short)Numbers[docID], FieldCache.DEFAULT.GetShorts(Ar, "number", false).Get(docID));
                            break;

                        case 2:
                            Assert.AreEqual((long)(int)Numbers[docID], FieldCache.DEFAULT.GetInts(Ar, "number", false).Get(docID));
                            break;

                        case 3:
                            Assert.AreEqual((long)Numbers[docID], FieldCache.DEFAULT.GetLongs(Ar, "number", false).Get(docID));
                            break;

                        case 4:
                            Assert.AreEqual(Number.IntBitsToFloat((int)Numbers[docID]), FieldCache.DEFAULT.GetFloats(Ar, "number", false).Get(docID), 0.0f);
                            break;

                        case 5:
                            Assert.AreEqual(BitConverter.Int64BitsToDouble((long)Numbers[docID]), FieldCache.DEFAULT.GetDoubles(Ar, "number", false).Get(docID), 0.0);
                            break;
                        }
                        bdv.Get(docID, scratch);
                        Assert.AreEqual(Binary[docID], scratch);
                        // Cannot share a single scratch against two "sources":
                        sdv.Get(docID, scratch2);
                        Assert.AreEqual(Sorted[docID], scratch2);
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message, e);
                }
            }
示例#8
0
        /// <summary>
        /// Test pausing and resuming during content playback.
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testPlaybackPauseResume() throws InterruptedException
        public virtual void testPlaybackPauseResume()
        {
//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(1);
            CountDownLatch latch = new CountDownLatch(1);

            eventEmitter.on(EventType.PROGRESS, new EventListenerAnonymousInnerClassHelper7(this, latch));

            assertTrue("Timeout occurred.", latch.@await(1, TimeUnit.MINUTES));
            assertTrue("Should have resumed.", hasResumed);
            assertTrue("Should not have repeated first five seconds: " + playheadPosition, playheadPosition > 5000);
        }
示例#9
0
        /// <summary>
        /// Test pausing and resuming during ad playback.
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testAdPauseResume() throws InterruptedException
        public virtual void testAdPauseResume()
        {
//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(1);
            CountDownLatch latch = new CountDownLatch(1);

            eventEmitter.on(GoogleIMAEventType.DID_START_AD, new EventListenerAnonymousInnerClassHelper8(this));

            eventEmitter.on(GoogleIMAEventType.DID_COMPLETE_AD, new EventListenerAnonymousInnerClassHelper9(this, latch));

            assertTrue("Timeout occurred.", latch.@await(1, TimeUnit.MINUTES));
            assertTrue("Should have resumed.", hasResumed);
        }
        //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 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);
     }
 }
示例#12
0
 public override IndexSearcher NewSearcher(IndexReader r)
 {
     try
     {
         if (TriedReopen.Get())
         {
             AwaitEnterWarm.countDown();
             AwaitClose.@await();
         }
     }
     catch (ThreadInterruptedException e)
     {
         //
     }
     return(new IndexSearcher(r, Es));
 }
示例#13
0
 public override void Run()
 {
     try
     {
         StartingGun.@await();
         w.AddDocument(Doc);
     }
     catch (System.ArgumentException iae)
     {
         // expected
         HitExc.Set(true);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message, e);
     }
 }
 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
     }
 }
            public override void Run()
            {
                try
                {
                    Latch.@await();
                }
                catch (ThreadInterruptedException e)
                {
                    throw new ThreadInterruptedException("Thread Interrupted Exception", e);
                }
                int i = 0;

                while ((i = Index.GetAndIncrement()) < Ids.Length)
                {
                    Term term = new Term("id", Ids[i].ToString());
                    Queue.Add(term, Slice);
                    Assert.IsTrue(Slice.IsTailItem(term));
                    Slice.Apply(Deletes, BufferedUpdates.MAX_INT);
                }
            }
示例#16
0
        /// <summary>
        /// Initialize Robotium, the BrightcoveVideoView and the EventEmitter.
        /// Start media playback. </summary>
        /// <exception cref="Exception"> </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override protected void setUp() throws Exception
        protected internal override void setUp()
        {
            base.setUp();
            ActivityInitialTouchMode = true;
            castActivity             = Activity;

            solo = new Solo(Instrumentation, castActivity);
            brightcoveVideoView = (BrightcoveVideoView)castActivity.findViewById(R.id.brightcove_video_view);
            eventEmitter        = brightcoveVideoView.EventEmitter;

//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);

            eventEmitter.once(EventType.DID_SET_VIDEO, new EventListenerAnonymousInnerClassHelper(this, countDownLatch));

            eventEmitter.once(EventType.DID_PLAY, new EventListenerAnonymousInnerClassHelper2(this, countDownLatch));

            assertTrue("Timeout occurred.", countDownLatch.@await(1, TimeUnit.MINUTES));
        }
示例#17
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;
     }
 }
示例#18
0
        /// <summary>
        /// Test for pre, mid, and post rolls.
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testPlay() throws InterruptedException
        public virtual void testPlay()
        {
//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(2);
            CountDownLatch latch = new CountDownLatch(2);

            Log.v(TAG, "testPlay");

            eventEmitter.on(GoogleIMAEventType.DID_START_AD, new EventListenerAnonymousInnerClassHelper2(this));

            eventEmitter.on(GoogleIMAEventType.DID_COMPLETE_AD, new EventListenerAnonymousInnerClassHelper3(this));

            eventEmitter.on(EventType.WILL_CHANGE_VIDEO, new EventListenerAnonymousInnerClassHelper4(this));

            eventEmitter.on(EventType.COMPLETED, new EventListenerAnonymousInnerClassHelper5(this, latch));

            assertTrue("Timeout occurred.", latch.@await(3, TimeUnit.MINUTES));
            brightcoveVideoView.stopPlayback();
            assertEquals("Should have played 2 prerolls.", 2, numPrerollsPlayed);
            assertEquals("Should have played 2 midrolls.", 2, numMidrollsPlayed);
            assertEquals("Should have played 2 postrolls.", 2, numPostrollsPlayed);
        }
            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);
                }
            }
示例#20
0
 public override void Run()
 {
     try
     {
         Document document = new Document();
         Field    field    = NewTextField("field", "", Field.Store.NO);
         document.Add(field);
         StartingGun.@await();
         while (!(Postings.Count == 0))
         {
             StringBuilder    text    = new StringBuilder();
             HashSet <string> visited = new HashSet <string>();
             for (int i = 0; i < MaxTermsPerDoc; i++)
             {
                 string token;
                 if (!Postings.TryDequeue(out token))
                 {
                     break;
                 }
                 if (visited.Contains(token))
                 {
                     // Put it back:
                     Postings.Enqueue(token);
                     break;
                 }
                 text.Append(' ');
                 text.Append(token);
                 visited.Add(token);
             }
             field.StringValue = text.ToString();
             Iw.AddDocument(document);
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message, e);
     }
 }
示例#21
0
        public virtual void TestOpenTwoIndexWritersOnDifferentThreads()
        {
            Directory      dir = NewDirectory();
            CountDownLatch oneIWConstructed      = new CountDownLatch(1);
            DelayedIndexAndCloseRunnable thread1 = new DelayedIndexAndCloseRunnable(dir, oneIWConstructed);
            DelayedIndexAndCloseRunnable thread2 = new DelayedIndexAndCloseRunnable(dir, oneIWConstructed);

            thread1.Start();
            thread2.Start();
            oneIWConstructed.@await();

            thread1.StartIndexing();
            thread2.StartIndexing();

            thread1.Join();
            thread2.Join();

            // ensure the directory is closed if we hit the timeout and throw assume
            // TODO: can we improve this in LuceneTestCase? I dont know what the logic would be...
            try
            {
                AssumeFalse("aborting test: timeout obtaining lock", thread1.Failure is LockObtainFailedException);
                AssumeFalse("aborting test: timeout obtaining lock", thread2.Failure is LockObtainFailedException);

                Assert.IsFalse(thread1.Failed, "Failed due to: " + thread1.Failure);
                Assert.IsFalse(thread2.Failed, "Failed due to: " + thread2.Failure);
                // now verify that we have two documents in the index
                IndexReader reader = DirectoryReader.Open(dir);
                Assert.AreEqual(2, reader.NumDocs, "IndexReader should have one document per thread running");

                reader.Dispose();
            }
            finally
            {
                dir.Dispose();
            }
        }
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //ORIGINAL LINE: void internalBlockUntilConnectedOrTimedOut() throws InterruptedException
        internal virtual void internalBlockUntilConnectedOrTimedOut()
        {
            long waitTimeMs = connectionTimeoutMs;
            while (!state.isConnected() && (waitTimeMs > 0))
            {
            //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(1);
                CountDownLatch latch = new CountDownLatch(1);
                Watcher tempWatcher = new WatcherAnonymousInnerClassHelper(this, latch);

                state.addParentWatcher(tempWatcher);
                var startTimeMs = TimeHelper.ElapsedMiliseconds;
                try
                {
                    latch.@await(1, TimeUnit.SECONDS);
                }
                finally
                {
                    state.removeParentWatcher(tempWatcher);
                }
                var elapsed = Math.Max(1, TimeHelper.ElapsedMiliseconds - startTimeMs);
                waitTimeMs -= elapsed;
            }
        }
        public void TestSessionTransactedCommitWithLocalPriorityReordering()
        {
            Mock <INmsConnectionListener> mockConnectionListener = new Mock <INmsConnectionListener>();
            CountDownLatch messagesArrived = new CountDownLatch(4);

            mockConnectionListener
            .Setup(listener => listener.OnInboundMessage(It.IsAny <NmsMessage>()))
            .Callback(() => { messagesArrived.countDown(); });

            Connection = CreateAmqpConnection();
            ((NmsConnection)Connection).AddConnectionListener(mockConnectionListener.Object);
            ISession session = Connection.CreateSession(AcknowledgementMode.Transactional);
            IQueue   queue   = session.GetQueue(TestName);

            Connection.Start();

            IMessageProducer producer = session.CreateProducer(queue);

            for (int i = 1; i <= 2; i++)
            {
                ITextMessage msg = session.CreateTextMessage("TestMessage" + i);
                msg.Properties.SetInt(MESSAGE_NUMBER, i);
                producer.Send(msg, MsgDeliveryMode.NonPersistent, NMSConstants.defaultPriority, NMSConstants.defaultTimeToLive);
            }

            session.Commit();

            // Receive first message.
            IMessageConsumer consumer = session.CreateConsumer(queue);
            IMessage         message  = consumer.Receive(TimeSpan.FromSeconds(5));

            Assert.NotNull(message);
            Assert.AreEqual(1, message.Properties.GetInt(MESSAGE_NUMBER));
            Assert.AreEqual(NMSConstants.defaultPriority, message.NMSPriority);

            // Send a couple higher priority, expect them to 'overtake' upon arrival at the consumer.
            for (int i = 3; i <= 4; i++)
            {
                ITextMessage msg = session.CreateTextMessage("TestMessage" + i);
                msg.Properties.SetInt(MESSAGE_NUMBER, i);
                producer.Send(msg, MsgDeliveryMode.NonPersistent, MsgPriority.High, NMSConstants.defaultTimeToLive);
            }

            session.Commit();

            // Wait for them all to arrive at the consumer
            Assert.True(messagesArrived.@await(TimeSpan.FromSeconds(5)));

            // Receive the other messages. Expect higher priority messages first.
            message = consumer.Receive(TimeSpan.FromSeconds(5));
            Assert.NotNull(message);
            Assert.AreEqual(3, message.Properties.GetInt(MESSAGE_NUMBER));
            Assert.AreEqual(MsgPriority.High, message.NMSPriority);

            message = consumer.Receive(TimeSpan.FromSeconds(5));
            Assert.NotNull(message);
            Assert.AreEqual(4, message.Properties.GetInt(MESSAGE_NUMBER));
            Assert.AreEqual(MsgPriority.High, message.NMSPriority);

            message = consumer.Receive(TimeSpan.FromSeconds(5));
            Assert.NotNull(message);
            Assert.AreEqual(2, message.Properties.GetInt(MESSAGE_NUMBER));
            Assert.AreEqual(NMSConstants.defaultPriority, message.NMSPriority);

            session.Commit();

            // Send a couple messages to check the session still works.
            for (int i = 5; i <= 6; i++)
            {
                ITextMessage msg = session.CreateTextMessage("TestMessage" + i);
                msg.Properties.SetInt(MESSAGE_NUMBER, i);
                producer.Send(msg, MsgDeliveryMode.NonPersistent, NMSConstants.defaultPriority, NMSConstants.defaultTimeToLive);
            }

            session.Commit();
            session.Close();
        }
        public virtual void TestStressMultiThreading()
        {
            Directory         dir    = NewDirectory();
            IndexWriterConfig conf   = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
            IndexWriter       writer = new IndexWriter(dir, conf);

            // create index
            int numThreads = TestUtil.NextInt(Random(), 3, 6);
            int numDocs    = AtLeast(2000);

            for (int i = 0; i < numDocs; i++)
            {
                Document doc = new Document();
                doc.Add(new StringField("id", "doc" + i, Store.NO));
                double group = Random().NextDouble();
                string g;
                if (group < 0.1)
                {
                    g = "g0";
                }
                else if (group < 0.5)
                {
                    g = "g1";
                }
                else if (group < 0.8)
                {
                    g = "g2";
                }
                else
                {
                    g = "g3";
                }
                doc.Add(new StringField("updKey", g, Store.NO));
                for (int j = 0; j < numThreads; j++)
                {
                    long value = Random().Next();
                    doc.Add(new BinaryDocValuesField("f" + j, TestBinaryDocValuesUpdates.ToBytes(value)));
                    doc.Add(new NumericDocValuesField("cf" + j, value * 2)); // control, always updated to f * 2
                }
                writer.AddDocument(doc);
            }

            CountDownLatch done       = new CountDownLatch(numThreads);
            AtomicInteger  numUpdates = new AtomicInteger(AtLeast(100));

            // same thread updates a field as well as reopens
            ThreadClass[] threads = new ThreadClass[numThreads];
            for (int i = 0; i < threads.Length; i++)
            {
                string f  = "f" + i;
                string cf = "cf" + i;
                threads[i] = new ThreadAnonymousInnerClassHelper(this, "UpdateThread-" + i, writer, numDocs, done, numUpdates, f, cf);
            }

            foreach (ThreadClass t in threads)
            {
                t.Start();
            }
            done.@await();
            writer.Dispose();

            DirectoryReader reader  = DirectoryReader.Open(dir);
            BytesRef        scratch = new BytesRef();

            foreach (AtomicReaderContext context in reader.Leaves)
            {
                AtomicReader r = context.AtomicReader;
                for (int i = 0; i < numThreads; i++)
                {
                    BinaryDocValues  bdv             = r.GetBinaryDocValues("f" + i);
                    NumericDocValues control         = r.GetNumericDocValues("cf" + i);
                    Bits             docsWithBdv     = r.GetDocsWithField("f" + i);
                    Bits             docsWithControl = r.GetDocsWithField("cf" + i);
                    Bits             liveDocs        = r.LiveDocs;
                    for (int j = 0; j < r.MaxDoc; j++)
                    {
                        if (liveDocs == null || liveDocs.Get(j))
                        {
                            Assert.AreEqual(docsWithBdv.Get(j), docsWithControl.Get(j));
                            if (docsWithBdv.Get(j))
                            {
                                long ctrlValue = control.Get(j);
                                long bdvValue  = TestBinaryDocValuesUpdates.GetValue(bdv, j, scratch) * 2;
                                //              if (ctrlValue != bdvValue) {
                                //                System.out.println("seg=" + r + ", f=f" + i + ", doc=" + j + ", group=" + r.Document(j).Get("updKey") + ", ctrlValue=" + ctrlValue + ", bdvBytes=" + scratch);
                                //              }
                                Assert.AreEqual(ctrlValue, bdvValue);
                            }
                        }
                    }
                }
            }
            reader.Dispose();

            dir.Dispose();
        }
示例#25
0
            public override void Run()
            {
                try
                {
                    IDictionary <string, int?> values = new Dictionary <string, int?>();
                    IList <string>             allIDs = new SynchronizedCollection <string>();

                    StartingGun.@await();
                    for (int iter = 0; iter < Iters; iter++)
                    {
                        // Add/update a document
                        Document doc = new Document();
                        // Threads must not update the same id at the
                        // same time:
                        if (ThreadRandom.NextDouble() <= AddChance)
                        {
                            string id    = string.Format(CultureInfo.InvariantCulture, "{0}_{1:X4}", ThreadID, ThreadRandom.Next(IdCount));
                            int    field = ThreadRandom.Next(int.MaxValue);
                            doc.Add(new StringField("id", id, Field.Store.YES));
                            doc.Add(new IntField("field", (int)field, Field.Store.YES));
                            w.UpdateDocument(new Term("id", id), doc);
                            Rt.Add(id, field);
                            if (!values.ContainsKey(id))//Key didn't exist before
                            {
                                allIDs.Add(id);
                            }
                            values[id] = field;
                        }

                        if (allIDs.Count > 0 && ThreadRandom.NextDouble() <= DeleteChance)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            w.DeleteDocuments(new Term("id", randomID));
                            Rt.Delete(randomID);
                            values[randomID] = Missing;
                        }

                        if (ThreadRandom.NextDouble() <= ReopenChance || Rt.Size() > 10000)
                        {
                            //System.out.println("refresh @ " + rt.Size());
                            Mgr.MaybeRefresh();
                            if (VERBOSE)
                            {
                                IndexSearcher s = Mgr.Acquire();
                                try
                                {
                                    Console.WriteLine("TEST: reopen " + s);
                                }
                                finally
                                {
                                    Mgr.Release(s);
                                }
                                Console.WriteLine("TEST: " + values.Count + " values");
                            }
                        }

                        if (ThreadRandom.Next(10) == 7)
                        {
                            Assert.AreEqual(null, Rt.Get("foo"));
                        }

                        if (allIDs.Count > 0)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            int?   expected = values[randomID];
                            if (expected == Missing)
                            {
                                expected = null;
                            }
                            Assert.AreEqual(expected, Rt.Get(randomID), "id=" + randomID);
                        }
                    }
                }
                catch (Exception t)
                {
                    throw new Exception(t.Message, t);
                }
            }
 public bool @await()
 {
     return(Waiter.@await(new TimeSpan(0, 0, 0, 10)));
 }
        public void TestConnectionStartStop()
        {
            using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password))
            {
                testAmqpPeer.Open();
                testAmqpPeer.RegisterMessageSource("myQueue");

                NmsConnectionFactory factory    = new NmsConnectionFactory(Address);
                IConnection          connection = factory.CreateConnection(User, Password);

                ISession session  = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IQueue   queue    = session.GetQueue("myQueue");
                var      consumer = session.CreateConsumer(queue);

                CountDownLatch firstBatch  = new CountDownLatch(5);
                CountDownLatch secondBatch = new CountDownLatch(5);

                consumer.Listener += message =>
                {
                    if (firstBatch.Remaining > 0)
                    {
                        firstBatch.countDown();
                    }
                    else
                    {
                        secondBatch.countDown();
                    }
                };

                // send first batch of messages
                for (int i = 0; i < 5; i++)
                {
                    testAmqpPeer.SendMessage("myQueue", $"message{i.ToString()}");
                }

                connection.Start();

                Assert.True(firstBatch.@await(TimeSpan.FromMilliseconds(1000)));

                // stop the connection, consumers shouldn't receive any more messages
                connection.Stop();

                // send second batch of messages
                for (int i = 5; i < 10; i++)
                {
                    testAmqpPeer.SendMessage("myQueue", $"message{i.ToString()}");
                }

                // No messages should arrive to consumer as connection has been stopped
                Assert.False(secondBatch.@await(TimeSpan.FromMilliseconds(1000)), "Message arrived despite the fact, that the connection was stopped.");

                // restart the connection
                connection.Start();

                // The second batch of messages should be delivered
                Assert.True(secondBatch.@await(TimeSpan.FromMilliseconds(1000)), "No messages arrived.");

                // Try closing them explicitly, should effectively no-op in client.
                // The test peer will throw during close if it sends anything.
                consumer.Close();
                session.Close();
                connection.Close();
            }
        }