예제 #1
0
        public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder)
        {
            IZookeeperFactory localZookeeperFactory = makeZookeeperFactory(builder.GetZookeeperFactory());
            this.client = new CuratorZookeeperClient(localZookeeperFactory,
                                                        builder.GetEnsembleProvider(),
                                                        builder.GetSessionTimeoutMs(),
                                                        builder.GetConnectionTimeoutMs(),
                                                        new WatchedWatcher(this),
                                                        builder.GetRetryPolicy(),
                                                        builder.CanBeReadOnly());

            listeners = new ListenerContainer<ICuratorListener>();
            unhandledErrorListeners = new ListenerContainer<IUnhandledErrorListener>();
            backgroundOperations = new DelayQueue<OperationAndData<object>>();
            @namespace = new NamespaceImpl(this, builder.GetNamespace());
            maxCloseWaitMs = builder.GetMaxCloseWaitMs();
            connectionStateManager = new ConnectionStateManager(this, builder.GetEventQueueSize());
            compressionProvider = builder.GetCompressionProvider();
            aclProvider = builder.GetAclProvider();
            state = new AtomicReference<CuratorFrameworkState>(CuratorFrameworkState.LATENT);
            useContainerParentsIfAvailable = builder.UseContainerParentsIfAvailable();

            byte[] builderDefaultData = builder.GetDefaultData();
            byte[] destDefaults = new byte[builderDefaultData.Length];
            Array.Copy(builderDefaultData, destDefaults, builderDefaultData.Length);
            defaultData = (builderDefaultData != null)
                            ?  destDefaults
                            : new byte[0];
            authInfos = buildAuths(builder);

            failedDeleteManager = new FailedDeleteManager(this);
            namespaceWatcherMap = new NamespaceWatcherMap(this);
            namespaceFacadeCache = new NamespaceFacadeCache(this);
        }
예제 #2
0
        public void CompareAndSet_when_equal_returns_true()
        {
            var expected = new object();
            var obj = new AtomicReference<object>(expected);

            Assert.IsTrue(obj.CompareAndSet(expected, new object()));
        }
예제 #3
0
        public void ToString_returns_a_string_representation_of_the_object()
        {
            var shared = new AtomicReference<object>();

            const string expected = "AtomicReference<System.Object>";

            Assert.AreEqual(expected, shared.ToString());
        }
        public void AtomicReference_IEquatable_Of_Ref_Should_Compare()
        {
            IEquatable<object> firstAtomic = new AtomicReference<object>(new object());
            IEquatable<object> secondAtomic = new AtomicReference<object>(null);

            Assert.False(firstAtomic.Equals(false));
            Assert.False(secondAtomic.Equals(true));
        }
예제 #5
0
 /// <summary>
 /// Initialize a reference to an on-disk object directory.
 /// </summary>
 /// <param name="dir">the location of the <code>objects</code> directory.</param>
 /// <param name="alternateObjectDir">a list of alternate object directories</param>
 public ObjectDirectory(DirectoryInfo dir, DirectoryInfo[] alternateObjectDir)
 {
     _objects = dir;
     _alternateObjectDir = alternateObjectDir;
     _infoDirectory = new DirectoryInfo(_objects.FullName + "/info");
     _packDirectory = new DirectoryInfo(_objects.FullName + "/pack");
     _alternatesFile = new FileInfo(_infoDirectory + "/alternates");
     _packList = new AtomicReference<PackList>(NoPacks);
 }
예제 #6
0
        public void Constructor_when_given_a_value_instantiates_with_it()
        {
            var value = new object();
            var obj = new AtomicReference<object>(value);

            var actual = obj.Value;

            Assert.AreEqual(value, actual);
        }
예제 #7
0
        public void GetAndSet_returns_old_value()
        {
            var value = new object();
            var obj = new AtomicReference<object>(value);

            var actual = obj.GetAndSet(new object());

            Assert.AreEqual(value, actual);
        }
예제 #8
0
        public void GetAndSet_sets_new_value()
        {
            var obj = new AtomicReference<object>();
            var value = new object();

            obj.GetAndSet(value);

            Assert.AreEqual(value, obj.Value);
        }
예제 #9
0
        public void CompareAndSet_when_not_equal_does_not_set_value()
        {
            var initial = new object();
            var obj = new AtomicReference<object>(initial);

            obj.CompareAndSet(new object(), new object());

            Assert.AreEqual(initial, obj.Value);
        }
예제 #10
0
 protected EnsurePath(String path, 
                         AtomicReference<Helper> helper, 
                         bool makeLastNode, 
                         IInternalACLProvider aclProvider)
 {
     this.path = path;
     this.makeLastNode = makeLastNode;
     this.aclProvider = aclProvider;
     this.helper = helper ?? new AtomicReference<Helper>(new InitialHelper(this));
 }
        public void AtomicReference_Implicit_Reassignment_Should_Change_Reference()
        {
            var firstAtomic = new AtomicReference<object>(new object());
            var secondAtomic = firstAtomic;

            firstAtomic = false;

            Assert.NotEqual(secondAtomic, firstAtomic);
            Assert.False(object.ReferenceEquals(secondAtomic, firstAtomic));
        }
        public void AtomicReference_Implicit_Ref_AcqRel_Should_Success()
        {
            var source = new object();
            var atomicReference = new AtomicReference<object>(source);

            var func = new Func<object, object>(i => i);

            Assert.NotEqual(source, func(atomicReference));
            Assert.Equal(source, func(atomicReference.Value));
        }
예제 #13
0
    public void ShouldNotUpdateWhenComparisonIsFalseAndReturnOldValue() {
      ReferenceMock reference = Reference;

      AtomicReference<ReferenceMock> ar =
        new AtomicReference<ReferenceMock>(reference);

      ReferenceMock new_mock = new ReferenceMock("new-mock");
      ReferenceMock old_mock = ar.CompareExchange(new_mock, new_mock);
      Assert.AreEqual(reference, ar.Value);
      Assert.AreEqual(reference, old_mock);
    }
예제 #14
0
    public void ShouldExchangeAndReturnOldValue() {
      ReferenceMock reference = Reference;

      AtomicReference<ReferenceMock> ar =
        new AtomicReference<ReferenceMock>(reference);

      ReferenceMock new_mock = new ReferenceMock("new_mock");
      ReferenceMock old_mock = ar.Exchange(new_mock);
      Assert.AreEqual(new_mock, ar.Value);
      Assert.AreEqual(reference, old_mock);
    }
        public void AtomicReference_Should_Implement_Reference_Equality()
        {
            var firstAtomic = new AtomicReference<object>(new object());
            var secondAtomic = new AtomicReference<object>(null);

            Assert.False(firstAtomic.Equals(secondAtomic));
            Assert.False(secondAtomic.Equals(firstAtomic));

            // self equality
            Assert.True(firstAtomic.Equals(firstAtomic));
            Assert.True(secondAtomic.Equals(secondAtomic));
        }
예제 #16
0
 public void Cache_should_be_updated_with_the_latest_resolved()
 {
     var localClock = new AtomicReference<long>(0);
     var cache = new SimpleDnsCacheTestDouble(localClock);
     var cacheEntryOne = Dns.Resolved.Create("test.local", System.Net.Dns.GetHostEntry("127.0.0.1").AddressList);
     var cacheEntryTwo = Dns.Resolved.Create("test.local", System.Net.Dns.GetHostEntry("127.0.0.1").AddressList);
     long ttl = 500;
     cache.Put(cacheEntryOne, ttl);
     cache.Cached("test.local").ShouldBe(cacheEntryOne);
     cache.Put(cacheEntryTwo, ttl);
     cache.Cached("test.local").ShouldBe(cacheEntryTwo);
 }
        public async Task TcpSocketChannel_should_not_throw_on_shutdown()
        {
            AtomicReference<Exception> clientError = new AtomicReference<Exception>(null);
            AtomicReference<Exception> serverError = new AtomicReference<Exception>(null);

            IChannel s = null;
            IChannel c = null;
            try
            {
                var sb = new ServerBootstrap()
                    .Channel<TcpServerSocketChannel>()
                    .ChildHandler(
                        new ActionChannelInitializer<TcpSocketChannel>(
                            channel => { channel.Pipeline.AddLast(new FailAssertionHandler(serverError)); }))
                    .Group(_serverGroup);

                s = sb.BindAsync(new IPEndPoint(IPAddress.IPv6Loopback, 0)).Result;


                var cb = new ClientBootstrap()
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                    .Handler(
                        new ActionChannelInitializer<TcpSocketChannel>(
                            channel => { channel.Pipeline.AddLast(new FailAssertionHandler(clientError)); }))
                    .Group(_clientGroup);

                var clientEp = s.LocalAddress;
                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);
                Assert.True(c.IsOpen);
                await c.CloseAsync();

                // assert that the counters were never decremented
                Assert.True(clientError.Value == null,
                    $"Expected null but error on client was {clientError.Value?.Message} {clientError.Value?.StackTrace}");
                Assert.True(serverError.Value == null,
                    $"Expected null but error on server was {serverError.Value?.Message} {serverError.Value?.StackTrace}");
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }
예제 #18
0
 public void TestHandlerAddedExecutedInEventLoop(int timeout)
 {
     var latch = new CountdownEvent(1);
     var ex = new AtomicReference<Exception>();
     IChannelHandler handler = new ChannelHandler3(latch, ex);
     var channel = new EmbeddedChannel(handler);
     Assert.False(channel.Finish());
     Assert.True(latch.Wait(timeout));
     var cause = ex.Value;
     if (cause != null)
     {
         throw cause;
     }
 }
예제 #19
0
        public void Cache_should_not_reply_with_expired_but_not_yet_swept_out_entries()
        {
            var localClock = new AtomicReference<long>(0);
            var cache = new SimpleDnsCacheTestDouble(localClock);
            var cacheEntry = Dns.Resolved.Create("test.local", System.Net.Dns.GetHostEntry("127.0.0.1").AddressList);
            cache.Put(cacheEntry, 5000);

            cache.Cached("test.local").ShouldBe(cacheEntry);
            localClock.CompareAndSet(0, 4999);
            cache.Cached("test.local").ShouldBe(cacheEntry);
            localClock.CompareAndSet(4999, 5000);
            cache.Cached("test.local").ShouldBe(null);

        }
예제 #20
0
        /// <summary>
        /// Creates a {@link InverseUserFrequency} transformation. Computations use the given log base.		 
        /// throws IllegalArgumentException if dataModel is <code>null</code> or logBase is {@link Double#NaN} or &lt;= 1.0
        /// </summary>
        /// <param name="dataModel">{@link DataModel} from which to calculate user frequencies</param>
        /// <param name="logBase">calculation logarithm base</param>
		public InverseUserFrequency(DataModel dataModel, double logBase) 
		{
			if (dataModel == null) 
			{
				throw new ArgumentNullException("dataModel is null");
			}
			if (double.IsNaN(logBase) || logBase <= 1.0) 
			{
				throw new ArgumentException("logBase is NaN or <= 1.0");
			}
			this.dataModel = dataModel;
			this.LogBase = logBase;
			this.iufFactors = new AtomicReference<Dictionary<Item, Double>>(new Dictionary<Item, Double>(1009));
			Refresh();
		}
예제 #21
0
        internal ConnectionState(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
            int sessionTimeoutMs, int connectionTimeoutMs, Watcher parentWatcher, AtomicReference<TracerDriver> tracer,
            bool canBeReadOnly)
        {
            this.ensembleProvider = ensembleProvider;
            this.sessionTimeoutMs = sessionTimeoutMs;
            this.connectionTimeoutMs = connectionTimeoutMs;
            this.tracer = tracer;
            if (parentWatcher != null)
            {
                parentWatchers.AddLast(parentWatcher);
            }

            zooKeeper = new HandleHolder(zookeeperFactory, this, ensembleProvider, sessionTimeoutMs, canBeReadOnly);
        }
        public void AtomicReference_Value_Change_Should_Success()
        {
            var source = new object();
            var atomicReference = new AtomicReference<object>(source);
            Assert.Equal(source, atomicReference.Value);

            atomicReference.Value = null;
            Assert.Null(atomicReference.Value);
            
            // same value assignment
            atomicReference.Value = source;
            Assert.Equal(source, atomicReference.Value);
            
            atomicReference.Value = source;
            Assert.Equal(source, atomicReference.Value);
        }
예제 #23
0
        public void Cache_should_sweep_out_expired_entries_on_cleanup()
        {
            var localClock = new AtomicReference<long>(0);
            var cache = new SimpleDnsCacheTestDouble(localClock);
            var cacheEntry = Dns.Resolved.Create("test.local", System.Net.Dns.GetHostEntry("127.0.0.1").AddressList);
            cache.Put(cacheEntry, 5000);

            cache.Cached("test.local").ShouldBe(cacheEntry);
            localClock.CompareAndSet(0, 5000);
            cache.Cached("test.local").ShouldBe(null);
            localClock.CompareAndSet(5000, 0);
            cache.Cached("test.local").ShouldBe(cacheEntry);
            localClock.CompareAndSet(0, 5000);
            cache.CleanUp();
            cache.Cached("test.local").ShouldBe(null);
            localClock.CompareAndSet(5000, 0);
            cache.Cached("test.local").ShouldBe(null);
           
        }
 public TestDirectMessageListenerContainer(SimpleRoutingConnectionFactory connectionFactory, AtomicReference <object> connectionMakerKey2)
     : base(null, connectionFactory, null, null)
 {
     this.connectionMakerKey2 = connectionMakerKey2;
     simpleFactory            = connectionFactory;
 }
예제 #25
0
 public ClusterListener_AdapterAnonymousInnerClass(ClusterTopologyChangesIT outerInstance, AtomicReference <InstanceId> coordinatorIdWhenReJoined, System.Threading.CountdownEvent latch)
 {
     this.outerInstance = outerInstance;
     this._coordinatorIdWhenReJoined = coordinatorIdWhenReJoined;
     this._latch = latch;
 }
예제 #26
0
 public ChannelHandler3(CountdownEvent latch, AtomicReference <Exception> error)
 {
     this.latch = latch;
     this.error = error;
 }
예제 #27
0
 public SimpleDnsCacheTestDouble(AtomicReference <long> clock)
 {
     _clock = clock;
 }
 public TestListener2(AtomicReference <RC.IModel> target, RC.IModel @object)
 {
     this.target  = target;
     this.@object = @object;
 }
            public ThreadAnonymousInnerClassHelper(BaseStoredFieldsFormatTestCase outerInstance, int numDocs, DirectoryReader rd, IndexSearcher searcher, int readsPerThread, AtomicReference <Exception> ex, int i)
            {
                this.OuterInstance  = outerInstance;
                this.NumDocs        = numDocs;
                this.Rd             = rd;
                this.Searcher       = searcher;
                this.ReadsPerThread = readsPerThread;
                this.Ex             = ex;
                this.i = i;

                queries = new int[ReadsPerThread];
                for (int j = 0; j < queries.Length; ++j)
                {
                    queries[j] = Random().NextIntBetween(0, NumDocs);
                }
            }
예제 #30
0
 ///	<summary>
 /// Create an empty configuration with a fallback for missing keys.
 ///	</summary>
 ///	<param name="defaultConfig">
 ///	the base configuration to be consulted when a key is missing
 /// from this configuration instance.
 /// </param>
 public Config(Config defaultConfig)
 {
     _baseConfig = defaultConfig;
     _state      = new AtomicReference <State>(newState());
 }
예제 #31
0
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: private static java.util.concurrent.Future<?> setPropertyInSeparateThreadAndAttemptToCommit(String threadName, org.neo4j.graphdb.GraphDatabaseService db, Object value, java.util.concurrent.CountDownLatch txStarted, java.util.concurrent.atomic.AtomicReference<org.neo4j.graphdb.Transaction> txReference)
        private static Future <object> SetPropertyInSeparateThreadAndAttemptToCommit(string threadName, GraphDatabaseService db, object value, System.Threading.CountdownEvent txStarted, AtomicReference <Transaction> txReference)
        {
            return(ExecuteInSeparateThread(threadName, () =>
            {
                using (Transaction tx = Db.beginTx())
                {
                    txReference.set(tx);
                    Node node = FindNode(db);
                    txStarted.Signal();
                    node.setProperty(PROPERTY, value);
                    tx.success();
                }
            }));
        }
예제 #32
0
 /// <summary>
 /// Initialize a new database instance for access.
 /// </summary>
 protected ObjectDatabase()
 {
     _alternates = new AtomicReference <ObjectDatabase[]>();
 }
예제 #33
0
 public Listener(AtomicReference <SortedSet <Member> > unexpected)
 {
     _unexpected = unexpected;
 }
예제 #34
0
 public SimpleDnsCache()
 {
     _cache     = new AtomicReference <Cache>(new Cache(new SortedSet <ExpiryEntry>(new ExpiryEntryComparer()), new Dictionary <string, CacheEntry>(), Clock));
     _ticksBase = DateTime.Now.Ticks;
 }
예제 #35
0
 public HttpPoolManager()
 {
     poolMapRef = new AtomicReference <ChannelPoolMapWrapper>();
 }
예제 #36
0
 public PackedRefsWriter(LockFile lck, RefList <Ref> refs, PackedRefList oldPackedList, AtomicReference <PackedRefList> packedRefs)
     : base(refs)
 {
     _lck           = lck;
     _refs          = refs;
     _oldPackedList = oldPackedList;
     _packedRefs    = packedRefs;
 }
예제 #37
0
 public ThreadAnonymousInnerClassHelper(TestIndexWriterWithThreads outerInstance, BaseDirectoryWrapper d, AtomicReference <IndexWriter> writerRef, LineFileDocs docs, int iters, AtomicBoolean failed, ReentrantLock rollbackLock, ReentrantLock commitLock)
 {
     this.OuterInstance = outerInstance;
     this.d             = d;
     this.WriterRef     = writerRef;
     this.Docs          = docs;
     this.Iters         = iters;
     this.Failed        = failed;
     this.RollbackLock  = rollbackLock;
     this.CommitLock    = commitLock;
 }
        public void AtomicReference_Equality_AcqRel_Should_Success()
        {
            var source = new object();
            var atomicReference = new AtomicReference<object>(source);

            Assert.True(atomicReference == source);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests()
        {
            // GIVEN
            Org.Neo4j.Test.Barrier_Control barrier           = new Org.Neo4j.Test.Barrier_Control();
            IOException controlledFailure                    = new IOException("My own fault");
            AtomicReference <Future <object> > secondRequest = new AtomicReference <Future <object> >();
            ThrowingAction <IOException>       controllableAndFailingAction = () =>
            {
                // Now that we know we're first, start the second request...
                secondRequest.set(T3.execute(state => _mutex.storeCopy(_assertNotCalled)));
                // ...and wait for it to reach its destination
                barrier.AwaitUninterruptibly();
                try
                {
                    // OK, second request has made progress into the request, so we can now produce our failure
                    throw controlledFailure;
                }
                finally
                {
                    barrier.Release();
                }
            };

            Future <object> firstRequest = T2.execute(state => _mutex.storeCopy(controllableAndFailingAction));

            while (secondRequest.get() == null)
            {
                ParkARandomWhile();
            }
            T3.get().waitUntilWaiting(details => details.isAt(typeof(StoreCopyCheckPointMutex), "waitForFirstStoreCopyActionToComplete"));

            // WHEN
            barrier.Reached();

            // THEN
            try
            {
                firstRequest.get();
            }
            catch (ExecutionException e)
            {
                assertSame(controlledFailure, e.InnerException);
            }
            try
            {
                secondRequest.get().get();
            }
            catch (ExecutionException e)
            {
                Exception cooperativeActionFailure = e.InnerException;
                assertThat(cooperativeActionFailure.Message, containsString("Co-operative"));
                assertSame(controlledFailure, cooperativeActionFailure.InnerException);
            }

            // WHEN afterwards trying another store-copy
            CountingAction action = new CountingAction();

            using (Resource @lock = _mutex.storeCopy(action))
            {
                // THEN
                assertEquals(1, action.Count());
            }
        }
예제 #40
0
 /// <summary>
 /// Construct an atom with given intiial value.
 /// </summary>
 /// <param name="state">The initial value</param>
 public Atom(object state)
 {
     _state = new AtomicReference<object>(state);
 }
        [Trait("Category", "SkipOnMacOS")] // TODO: Figure out why
        public async Task TestDeferredAcks()
        {
            var connectionFactory = new Mock <Connection.IConnectionFactory>();
            var connection        = new Mock <Connection.IConnection>();
            var channel           = new Mock <IChannelProxy>();
            var rabbitChannel     = new Mock <RC.IModel>();

            channel.Setup(c => c.TargetChannel).Returns(rabbitChannel.Object);
            connectionFactory.Setup((f) => f.CreateConnection()).Returns(connection.Object);
            connection.Setup((c) => c.CreateChannel(It.IsAny <bool>())).Returns(channel.Object);
            connection.Setup((c) => c.IsOpen).Returns(true);
            channel.Setup((c) => c.IsOpen).Returns(true);
            rabbitChannel.Setup(c => c.CreateBasicProperties()).Returns(new MockRabbitBasicProperties());
            channel.Setup(c => c.QueueDeclarePassive(It.IsAny <string>())).Returns(new RC.QueueDeclareOk("test", 0, 0));

            var consumer = new AtomicReference <RC.IBasicConsumer>();
            var latch1   = new CountdownEvent(1);

            channel.Setup(c =>
                          c.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <RC.IBasicConsumer>()))
            .Callback <string, bool, string, bool, bool, IDictionary <string, object>, RC.IBasicConsumer>(
                (queue, autoAck, consumerTag, noLocal, exclusive, args, cons) =>
            {
                consumer.Value = cons;
                cons.HandleBasicConsumeOk("consumerTag");
                latch1.Signal();
            })
            .Returns("consumerTag");
            var qos = new AtomicInteger();

            channel.Setup(c => c.BasicQos(It.IsAny <uint>(), It.IsAny <ushort>(), It.IsAny <bool>()))
            .Callback <uint, ushort, bool>((size, count, global) =>
            {
                qos.Value = count;
            });
            var latch2 = new CountdownEvent(1);
            var latch3 = new CountdownEvent(1);

            channel.Setup(c => c.BasicAck(It.IsAny <ulong>(), It.IsAny <bool>()))
            .Callback <ulong, bool>((tag, multi) =>
            {
                if (tag == 10ul || tag == 16ul)
                {
                    latch2.Signal();
                }
                else if (tag == 17ul)
                {
                    latch3.Signal();
                }
            });
            var latch4 = new CountdownEvent(1);

            channel.Setup(c => c.BasicNack(It.IsAny <ulong>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .Callback <ulong, bool, bool>((tag, multi, re) =>
            {
                latch4.Signal();
            });
            var container = new DirectMessageListenerContainer(null, connectionFactory.Object);

            container.SetQueueNames("test");
            container.PrefetchCount   = 2;
            container.MonitorInterval = 100;
            container.MessagesPerAck  = 10;
            container.AckTimeout      = 100;
            container.MessageListener = new TestListener();
            container.Initialize();
            await container.Start();

            Assert.True(container._startedLatch.Wait(TimeSpan.FromSeconds(10)));

            Assert.True(latch1.Wait(TimeSpan.FromSeconds(10)));
            Assert.Equal(10, qos.Value);
            var props = new MockRabbitBasicProperties();

            var body = new byte[1];

            for (long i = 1; i < 16; i++)
            {
                consumer.Value.HandleBasicDeliver("consumerTag", (ulong)i, false, string.Empty, string.Empty, props, body);
            }

            Thread.Sleep(200);

            consumer.Value.HandleBasicDeliver("consumerTag", 16ul, false, string.Empty, string.Empty, props, body);

            // should get 2 acks #10 and #16 (timeout)
            Assert.True(latch2.Wait(TimeSpan.FromSeconds(10)));
            consumer.Value.HandleBasicDeliver("consumerTag", 17ul, false, string.Empty, string.Empty, props, body);
            channel.Verify(c => c.BasicAck(10ul, true));
            channel.Verify(c => c.BasicAck(15ul, true));

            Assert.True(latch3.Wait(TimeSpan.FromSeconds(10)));

            // monitor task timeout
            channel.Verify(c => c.BasicAck(17ul, true));
            consumer.Value.HandleBasicDeliver("consumerTag", 18ul, false, string.Empty, string.Empty, props, body);
            consumer.Value.HandleBasicDeliver("consumerTag", 19ul, false, string.Empty, string.Empty, props, body);
            Assert.True(latch4.Wait(TimeSpan.FromSeconds(10)));

            // pending acks before nack
            channel.Verify(c => c.BasicAck(18ul, true));
            channel.Verify(c => c.BasicNack(19ul, true, true));
            consumer.Value.HandleBasicDeliver("consumerTag", 20ul, false, string.Empty, string.Empty, props, body);
            var latch5 = new CountdownEvent(1);

            channel.Setup(c => c.BasicCancel("consumerTag"))
            .Callback(() =>
            {
                consumer.Value.HandleBasicCancelOk("consumerTag");
                latch5.Signal();
            });

            await container.Stop();

            Assert.True(latch5.Wait(TimeSpan.FromSeconds(10)));
            channel.Verify((c) => c.BasicAck(20ul, true));
        }
예제 #42
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private long[] repeatCreateNamedPeopleFor(int totalNumberOfPeople) throws Exception
        private long[] RepeatCreateNamedPeopleFor(int totalNumberOfPeople)
        {
            // Parallelize the creation of persons
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long[] nodes = new long[totalNumberOfPeople];
            long[]    nodes   = new long[totalNumberOfPeople];
            const int threads = 100;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int peoplePerThread = totalNumberOfPeople / threads;
            int peoplePerThread = totalNumberOfPeople / threads;

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.ExecutorService service = java.util.concurrent.Executors.newFixedThreadPool(threads);
            ExecutorService service = Executors.newFixedThreadPool(threads);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<org.neo4j.internal.kernel.api.exceptions.KernelException> exception = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <KernelException> exception = new AtomicReference <KernelException>();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<java.util.concurrent.Callable<Void>> jobs = new java.util.ArrayList<>(threads);
            IList <Callable <Void> > jobs = new List <Callable <Void> >(threads);

            // Start threads that creates these people, relying on batched writes to speed things up
            for (int i = 0; i < threads; i++)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int finalI = i;
                int finalI = i;

                jobs.Add(() =>
                {
                    int offset = finalI * peoplePerThread;
                    while (offset < (finalI + 1) * peoplePerThread)
                    {
                        try
                        {
                            offset += CreateNamedPeople(nodes, offset);
                        }
                        catch (KernelException e)
                        {
                            exception.compareAndSet(null, e);
                            throw new Exception(e);
                        }
                    }
                    return(null);
                });
            }

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.concurrent.Future<?> job : service.invokeAll(jobs))
            foreach (Future <object> job in service.invokeAll(jobs))
            {
                job.get();
            }

            service.awaitTermination(1, TimeUnit.SECONDS);
            service.shutdown();

            // Make any KernelException thrown from a creation thread visible in the main thread
            Exception ex = exception.get();

            if (ex != null)
            {
                throw ex;
            }

            return(nodes);
        }
        public async Task TestRemoveQueuesWhileNotConnected()
        {
            var connectionFactory = new Mock <Connection.IConnectionFactory>();
            var connection        = new Mock <Connection.IConnection>();
            var channel           = new Mock <IChannelProxy>();
            var rabbitChannel     = new Mock <RC.IModel>();

            channel.Setup(c => c.TargetChannel).Returns(rabbitChannel.Object);

            connectionFactory.Setup((f) => f.CreateConnection()).Returns(connection.Object);
            connection.Setup((c) => c.CreateChannel(It.IsAny <bool>())).Returns(channel.Object);
            connection.Setup((c) => c.IsOpen).Returns(true);
            var isOpen = new AtomicBoolean(true);

            channel.Setup((c) => c.IsOpen).Returns(
                () =>
                isOpen.Value);
            rabbitChannel.Setup(c => c.CreateBasicProperties()).Returns(new MockRabbitBasicProperties());

            var declare = new AtomicReference <string>();

            channel.Setup(c => c.QueueDeclarePassive(It.IsAny <string>()))
            .Callback <string>(
                (name) =>
                declare.Value = name)
            .Returns(() =>
                     new RC.QueueDeclareOk(declare.Value, 0, 0));

            var latch1 = new CountdownEvent(2);
            var latch3 = new CountdownEvent(3);

            channel.Setup(c =>
                          c.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <RC.IBasicConsumer>()))
            .Callback(
                () =>
            {
                if (!latch3.IsSet)
                {
                    latch3.Signal();
                }
            })
            .Returns("consumerTag");
            var qos = new AtomicInteger();

            channel.Setup(c => c.BasicQos(It.IsAny <uint>(), It.IsAny <ushort>(), It.IsAny <bool>()))
            .Callback <uint, ushort, bool>((size, count, global) =>
            {
                qos.Value = count;
                if (!latch1.IsSet)
                {
                    latch1.Signal();
                }
            });

            var latch2 = new CountdownEvent(2);

            channel.Setup(
                c => c.BasicCancel("consumerTag"))
            .Callback(
                () =>
            {
                if (!latch2.IsSet)
                {
                    latch2.Signal();
                }
            });

            var container = new DirectMessageListenerContainer(null, connectionFactory.Object);

            container.SetQueueNames("test1", "test2");
            container.PrefetchCount   = 2;
            container.MonitorInterval = 100;
            container.FailedDeclarationRetryInterval = 100;
            container.RecoveryInterval = 100;
            container.ShutdownTimeout  = 1;
            container.Initialize();
            await container.Start();

            Assert.True(container._startedLatch.Wait(TimeSpan.FromSeconds(10)));

            Assert.True(latch1.Wait(TimeSpan.FromSeconds(10)));
            Assert.Equal(2, qos.Value);
            isOpen.Value = false;
            container.RemoveQueueNames("test1");
            Assert.True(latch2.Wait(TimeSpan.FromSeconds(20))); // Basic Cancels from isOpen = false
            isOpen.Value = true;                                // Consumers should restart, but only test2,
            Assert.True(latch3.Wait(TimeSpan.FromSeconds(10)));

            channel.Verify(
                c =>
                c.BasicConsume("test1", It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <RC.IBasicConsumer>()),
                Times.Once());
            channel.Verify(
                c =>
                c.BasicConsume("test2", It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <RC.IBasicConsumer>()),
                Times.Exactly(2));
            await container.Stop();
        }
예제 #44
0
        /**
         * Initialize a reference to an on-disk object directory.
         *
         * @param dir
         *            the location of the <code>objects</code> directory.
         */
        public ObjectDirectory(DirectoryInfo dir)
        {
            objects = dir;
            infoDirectory = new DirectoryInfo(objects.FullName + "/info");
            packDirectory = new DirectoryInfo(objects.FullName + "/pack");
            alternatesFile = new FileInfo(infoDirectory + "/alternates");

            packList = new AtomicReference<PackFile[]>();
        }
예제 #45
0
            public ThreadAnonymousClass(int numDocs, DirectoryReader rd, IndexSearcher searcher, int readsPerThread, AtomicReference <Exception> ex)
            {
                this.numDocs        = numDocs;
                this.rd             = rd;
                this.searcher       = searcher;
                this.readsPerThread = readsPerThread;
                this.ex             = ex;

                queries = new int[this.readsPerThread];
                for (int j = 0; j < queries.Length; ++j)
                {
                    queries[j] = Random.Next(this.numDocs);
                }
            }
예제 #46
0
 public ChannelInboundHandlerAdapter0(AtomicReference <IChannelHandlerContext> ctxRef, AtomicReference <PendingWriteQueue> queueRef)
 {
     _ctxRef   = ctxRef;
     _queueRef = queueRef;
 }
예제 #47
0
 public TestContext(int times)
 {
     Access    = AccessSafely.AfterCompleting(times);
     reference = new AtomicReference <object>();
     SetUpWriteRead();
 }
 public ThreadAnonymousClass(BaseTermVectorsFormatTestCase outerInstance, int numDocs, RandomDocument[] docs, IndexReader reader, AtomicReference <Exception> exception)
 {
     this.outerInstance = outerInstance;
     this.numDocs       = numDocs;
     this.docs          = docs;
     this.reader        = reader;
     this.exception     = exception;
 }
        public void AtomicReference_Equality_SeqCst_Should_Success()
        {
            var source = new object();
            var atomicReference = new AtomicReference<object>(source, MemoryOrder.SeqCst);

            Assert.True(atomicReference == source);
        }
            public ThreadAnonymousInnerClassHelper(TestIndexWriterWithThreads outerInstance, BaseDirectoryWrapper d, AtomicReference <IndexWriter> writerRef, LineFileDocs docs, int iters, AtomicBoolean failed, ReentrantLock rollbackLock, ReentrantLock commitLock)
            {
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
                this.outerInstance = outerInstance;
#endif
                this.d            = d;
                this.writerRef    = writerRef;
                this.docs         = docs;
                this.iters        = iters;
                this.failed       = failed;
                this.rollbackLock = rollbackLock;
                this.commitLock   = commitLock;
            }
        public void AtomicReference_Inequality_SeqCst_Should_Success()
        {
            var atomicReference = new AtomicReference<object>(null, MemoryOrder.SeqCst);

            Assert.False(atomicReference != null);
        }
예제 #52
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void shouldShutdownEvenThoughWaitingForLock0(org.neo4j.causalclustering.discovery.Cluster<?> cluster, int victimId, java.util.Collection<int> shutdownOrder) throws Exception
        private void ShouldShutdownEvenThoughWaitingForLock0 <T1>(Cluster <T1> cluster, int victimId, ICollection <int> shutdownOrder)
        {
            const int longTime = 60_000;
            const int numberOfLockAcquirers = 2;

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.ExecutorService txExecutor = java.util.concurrent.Executors.newCachedThreadPool();
            ExecutorService txExecutor = Executors.newCachedThreadPool();               // Blocking transactions are executed in
            // parallel, not on the main thread.
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.ExecutorService shutdownExecutor = java.util.concurrent.Executors.newFixedThreadPool(1);
            ExecutorService shutdownExecutor = Executors.newFixedThreadPool(1);                 // Shutdowns are executed

            // serially, not on the main thread.

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch acquiredLocksCountdown = new java.util.concurrent.CountDownLatch(NUMBER_OF_LOCK_ACQUIRERS);
            System.Threading.CountdownEvent acquiredLocksCountdown = new System.Threading.CountdownEvent(numberOfLockAcquirers);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch locksHolder = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent locksHolder = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<org.neo4j.graphdb.Node> node = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <Node> node = new AtomicReference <Node>();

            CompletableFuture <Void> preShutdown = new CompletableFuture <Void>();

            // set shutdown order
            CompletableFuture <Void> afterShutdown = preShutdown;

            foreach (int?id in shutdownOrder)
            {
                afterShutdown = afterShutdown.thenRunAsync(() => cluster.GetCoreMemberById(id.Value).shutdown(), shutdownExecutor);
            }

            CreateANode(node);

            try
            {
                // when - blocking on lock acquiring
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.graphdb.GraphDatabaseService leader = cluster.getCoreMemberById(victimId).database();
                GraphDatabaseService leader = cluster.GetCoreMemberById(victimId).database();

                for (int i = 0; i < numberOfLockAcquirers; i++)
                {
                    txExecutor.execute(() =>
                    {
                        try
                        {
                            using (Transaction tx = leader.BeginTx())
                            {
                                acquiredLocksCountdown.Signal();
                                tx.acquireWriteLock(node.get());
                                locksHolder.await();
                                tx.success();
                            }
                        }
                        catch (Exception)
                        {
                            /* Since we are shutting down, a plethora of possible exceptions are expected. */
                        }
                    });
                }

                // await locks
                if (!acquiredLocksCountdown.await(longTime, MILLISECONDS))
                {
                    throw new System.InvalidOperationException("Failed to acquire locks");
                }

                // then shutdown in given order works
                preShutdown.complete(null);
                afterShutdown.get(longTime, MILLISECONDS);
            }
            finally
            {
                afterShutdown.cancel(true);
                locksHolder.Signal();
                txExecutor.shutdownNow();
                shutdownExecutor.shutdownNow();
            }
        }
예제 #53
0
 public TestMailbox()
 {
     world = TestWorld.Instance !;
     queue = new ConcurrentQueue <IMessage>();
     suspendedOverrides = new AtomicReference <Stack <List <Type> > >(new Stack <List <Type> >());
 }
예제 #54
0
 public FailAssertionHandler(AtomicReference <Exception> ex)
 {
     _ex = ex;
 }
예제 #55
0
            public Logic(OutputStreamSourceStage stage, BlockingCollection <ByteString> dataQueue, AtomicReference <IDownstreamStatus> downstreamStatus, string dispatcherId) : base(stage.Shape)
            {
                _stage            = stage;
                _dataQueue        = dataQueue;
                _downstreamStatus = downstreamStatus;
                _dispatcherId     = dispatcherId;

                var downstreamCallback = GetAsyncCallback((Either <ByteString, Exception> result) =>
                {
                    if (result.IsLeft)
                    {
                        OnPush(result.Value as ByteString);
                    }
                    else
                    {
                        FailStage(result.Value as Exception);
                    }
                });

                _upstreamCallback =
                    GetAsyncCallback <Tuple <IAdapterToStageMessage, TaskCompletionSource <NotUsed> > >(OnAsyncMessage);
                _pullTask = new OnPullRunnable(downstreamCallback, dataQueue, _cancellation.Token);
                SetHandler(_stage._out, onPull: OnPull, onDownstreamFinish: OnDownstreamFinish);
            }
예제 #56
0
 public TestRecoveryCallback(AtomicReference <IMessage> replyMessage, AtomicReference <Address> replyAddress, AtomicReference <Exception> throwable)
 {
     this.replyMessage = replyMessage;
     this.replyAddress = replyAddress;
     this.throwable    = throwable;
 }
        public void AtomicReference_Inequality_AcqRel_Should_Success()
        {
            var atomicReference = new AtomicReference<object>(null);

            Assert.True(atomicReference == null);
            Assert.False(object.ReferenceEquals(atomicReference, null));
        }
예제 #58
0
 public _Answer_205(AtomicReference <DatanodeProtocolProtos.BlockReportRequestProto
                                     > request)
 {
     this.request = request;
 }
예제 #59
0
 /// <summary>
 /// Construct an atom with given initial value and metadata.
 /// </summary>
 /// <param name="state">The initial value.</param>
 /// <param name="meta">The metadata to attach.</param>
 public Atom(object state, IPersistentMap meta)
     : base(meta)
 {
     _state = new AtomicReference<object>(state);
 }
예제 #60
0
        public void TestRecoverAfterDeletedQueueAndLostConnection()
        {
            var connectionFactory = new Mock <IConnectionFactory>();
            var connection        = new Mock <IConnection>();
            var channel           = new Mock <R.IModel>();

            connectionFactory.Setup((f) => f.CreateConnection()).Returns(connection.Object);
            connection.Setup(c => c.CreateChannel(It.IsAny <bool>())).Returns(channel.Object);
            connection.Setup(c => c.IsOpen).Returns(true);
            channel.Setup(c => c.IsOpen).Returns(true);
            var n = new AtomicInteger();
            var consumerCaptor = new AtomicReference <R.IBasicConsumer>();
            var consumerLatch  = new CountdownEvent(2);

            channel.Setup(c => c.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <R.IBasicConsumer>()))
            .Callback <string, bool, string, bool, bool, IDictionary <string, object>, R.IBasicConsumer>((a1, a2, a3, a4, a5, a6, a7) =>
            {
                consumerCaptor.Value = a7;
                consumerLatch.Signal();
            })
            .Returns("consumer" + n.IncrementAndGet());
            channel.Setup(c => c.BasicCancel("consumer2"))
            .Throws(new Exception("Intentional cancel fail"));
            var blockingQueueConsumer = new BlockingQueueConsumer(
                connectionFactory.Object,
                new DefaultMessageHeadersConverter(),
                new ActiveObjectCounter <BlockingQueueConsumer>(),
                AcknowledgeMode.AUTO,
                false,
                1,
                null,
                "testQ1",
                "testQ2");
            var latch = new CountdownEvent(1);

            Task.Run(() =>
            {
                blockingQueueConsumer.Start();
                while (true)
                {
                    try
                    {
                        blockingQueueConsumer.NextMessage(1000);
                    }
                    catch (ConsumerCancelledException)
                    {
                        latch.Signal();
                        break;
                    }
                    catch (ShutdownSignalException)
                    {
                        // Noop
                    }
                    catch (Exception)
                    {
                        // noop
                    }
                }
            });
            Assert.True(consumerLatch.Wait(TimeSpan.FromSeconds(10)));
            var consumer = consumerCaptor.Value;

            consumer.HandleBasicCancel("consumer1");
            Assert.True(latch.Wait(TimeSpan.FromSeconds(10)));
        }