Exemplo n.º 1
0
 public override void outputFileCreated(Stream @out)
 {
     try
     {
         Thread thread = new Thread(() =>
         {
             try
             {
                 @out.WriteByte(logContent.Bytes);
                 @out.Flush();
             }
             catch (IOException e)
             {
                 _listenerException.set(e);
             }
         });
         thread.Start();
         thread.Join();
     }
     catch (Exception e)
     {
         _listenerException.set(e);
     }
     base.outputFileCreated(@out);
 }
Exemplo n.º 2
0
 /// <summary>
 /// Fully close all loaded alternates and clear the alternate list.
 /// </summary>
 public virtual void closeAlternates()
 {
     ObjectDatabase[] alt = _alternates.get();
     if (alt != null)
     {
         _alternates.set(null);
         closeAlternates(alt);
     }
 }
Exemplo n.º 3
0
		 public override void TransactionCommitted( long transactionId, long checksum, long commitTimestamp )
		 {
			 lock ( this )
			 {
				  TransactionId current = _committedTransactionId.get();
				  if ( current == null || transactionId > current.TransactionIdConflict() )
				  {
						_committedTransactionId.set( new TransactionId( transactionId, checksum, commitTimestamp ) );
				  }
			 }
		 }
Exemplo n.º 4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldTimeoutIfTheIndexTakesTooLongToComeOnline() throws InterruptedException, org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldTimeoutIfTheIndexTakesTooLongToComeOnline()
        {
            when(_tokenRead.nodeLabel(anyString())).thenReturn(0);
            when(_tokenRead.propertyKey(anyString())).thenReturn(0);
            when(_schemaRead.index(anyInt(), anyInt())).thenReturn(_anyIndex);
            when(_schemaRead.indexGetState(any(typeof(IndexReference)))).thenReturn(POPULATING);

            AtomicReference <ProcedureException> exception = new AtomicReference <ProcedureException>();

            (new Thread(() =>
            {
                try
                {
                    // We wait here, because we expect timeout
                    _procedure.awaitIndexByPattern(":Person(name)", 0, _timeUnit);
                }
                catch (ProcedureException e)
                {
                    exception.set(e);
                }
            })).Start();

            assertEventually("Procedure did not time out", exception.get, not(nullValue()), TIMEOUT, _timeUnit);
            //noinspection ThrowableResultOfMethodCallIgnored
            assertThat(exception.get().status(), @is(Org.Neo4j.Kernel.Api.Exceptions.Status_Procedure.ProcedureTimedOut));
        }
Exemplo n.º 5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createdWorkerThreadsShouldContainConnectorNameAndRemoteAddressInTheirNamesWhenActive() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CreatedWorkerThreadsShouldContainConnectorNameAndRemoteAddressInTheirNamesWhenActive()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<String> capturedThreadName = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <string> capturedThreadName = new AtomicReference <string>();

            AtomicInteger  processNextBatchCount = new AtomicInteger();
            string         id            = System.Guid.randomUUID().ToString();
            BoltConnection connection    = NewConnection(id);
            AtomicBoolean  exitCondition = new AtomicBoolean();

            when(connection.ProcessNextBatch()).thenAnswer(inv =>
            {
                capturedThreadName.set(Thread.CurrentThread.Name);
                processNextBatchCount.incrementAndGet();
                return(AwaitExit(exitCondition));
            });

            _boltScheduler.start();
            _boltScheduler.created(connection);
            _boltScheduler.enqueued(connection, Jobs.noop());

            Predicates.await(() => processNextBatchCount.get() > 0, 1, MINUTES);

            assertThat(capturedThreadName.get(), containsString(string.Format("[{0}]", CONNECTOR_KEY)));
            assertThat(capturedThreadName.get(), containsString(string.Format("[{0}]", connection.RemoteAddress())));

            exitCondition.set(true);
        }
Exemplo n.º 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createdWorkerThreadsShouldContainConnectorName() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CreatedWorkerThreadsShouldContainConnectorName()
        {
            AtomicInteger            executeBatchCompletionCount = new AtomicInteger();
            AtomicReference <Thread> poolThread     = new AtomicReference <Thread>();
            AtomicReference <string> poolThreadName = new AtomicReference <string>();

            string         id         = System.Guid.randomUUID().ToString();
            BoltConnection connection = NewConnection(id);

            when(connection.HasPendingJobs()).thenAnswer(inv =>
            {
                executeBatchCompletionCount.incrementAndGet();
                return(false);
            });
            when(connection.ProcessNextBatch()).thenAnswer(inv =>
            {
                poolThread.set(Thread.CurrentThread);
                poolThreadName.set(Thread.CurrentThread.Name);
                return(true);
            });

            _boltScheduler.start();
            _boltScheduler.created(connection);
            _boltScheduler.enqueued(connection, Jobs.noop());

            Predicates.await(() => executeBatchCompletionCount.get() > 0, 1, MINUTES);

            assertThat(poolThread.get().Name, not(equalTo(poolThreadName.get())));
            assertThat(poolThread.get().Name, containsString(string.Format("[{0}]", CONNECTOR_KEY)));
            assertThat(poolThread.get().Name, not(containsString(string.Format("[{0}]", connection.RemoteAddress()))));
        }
Exemplo n.º 7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void terminatedTransactionDoesNotForceUpdatePulling()
        public virtual void TerminatedTransactionDoesNotForceUpdatePulling()
        {
            int testTxsOnMaster = 42;

            ClusterManager.ManagedCluster cluster = ClusterRule.withSharedSetting(HaSettings.pull_interval, "0s").withSharedSetting(HaSettings.tx_push_factor, "0").startCluster();

            HighlyAvailableGraphDatabase master = cluster.Master;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.ha.HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
            HighlyAvailableGraphDatabase slave = cluster.AnySlave;

            CreateNodeOn(master);
            cluster.Sync();

            long lastClosedTxIdOnMaster = LastClosedTxIdOn(master);
            long lastClosedTxIdOnSlave  = LastClosedTxIdOn(slave);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch slaveTxStarted = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent slaveTxStarted = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch slaveShouldCommit = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent slaveShouldCommit = 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.Transaction> slaveTx = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <Transaction> slaveTx = new AtomicReference <Transaction>();
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> slaveCommit = java.util.concurrent.Executors.newSingleThreadExecutor().submit(() ->
            Future <object> slaveCommit = Executors.newSingleThreadExecutor().submit(() =>
            {
                using (Transaction tx = slave.BeginTx())
                {
                    slaveTx.set(tx);
                    slaveTxStarted.Signal();
                    Await(slaveShouldCommit);
                    tx.success();
                }
            });

            Await(slaveTxStarted);
            CreateNodesOn(master, testTxsOnMaster);

            assertNotNull(slaveTx.get());
            slaveTx.get().terminate();
            slaveShouldCommit.Signal();

            try
            {
                slaveCommit.get();
                fail("Exception expected");
            }
            catch (Exception e)
            {
                assertThat(e, instanceOf(typeof(ExecutionException)));
                assertThat(e.InnerException, instanceOf(typeof(TransientTransactionFailureException)));
            }

            assertEquals(lastClosedTxIdOnMaster + testTxsOnMaster, LastClosedTxIdOn(master));
            assertEquals(lastClosedTxIdOnSlave, LastClosedTxIdOn(slave));
        }
Exemplo n.º 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldGetSpecifiedUsernameAndMetaDataInTXData()
        public virtual void ShouldGetSpecifiedUsernameAndMetaDataInTXData()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<String> usernameRef = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <string> usernameRef = new AtomicReference <string>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<java.util.Map<String,Object>> metaDataRef = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <IDictionary <string, object> > metaDataRef = new AtomicReference <IDictionary <string, object> >();

            _db.registerTransactionEventHandler(GetBeforeCommitHandler(txData =>
            {
                usernameRef.set(txData.username());
                metaDataRef.set(txData.metaData());
            }));
            AuthSubject subject = mock(typeof(AuthSubject));

            when(subject.Username()).thenReturn("Christof");
            LoginContext loginContext             = new LoginContextAnonymousInnerClass(this, subject);
            IDictionary <string, object> metadata = genericMap("username", "joe");

            RunTransaction(loginContext, metadata);

            assertThat("Should have specified username", usernameRef.get(), equalTo("Christof"));
            assertThat("Should have metadata with specified username", metaDataRef.get(), equalTo(metadata));
        }
Exemplo n.º 9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBlockUntilTheIndexIsOnline() throws org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBlockUntilTheIndexIsOnline()
        {
            when(_tokenRead.nodeLabel(anyString())).thenReturn(0);
            when(_tokenRead.propertyKey(anyString())).thenReturn(0);
            when(_schemaRead.index(anyInt(), any())).thenReturn(_anyIndex);

            AtomicReference <InternalIndexState> state = new AtomicReference <InternalIndexState>(POPULATING);

            when(_schemaRead.indexGetState(any(typeof(IndexReference)))).then(invocationOnMock => state.get());

            AtomicBoolean done = new AtomicBoolean(false);

            (new Thread(() =>
            {
                try
                {
                    _procedure.awaitIndexByPattern(":Person(name)", TIMEOUT, _timeUnit);
                }
                catch (ProcedureException e)
                {
                    throw new Exception(e);
                }
                done.set(true);
            })).Start();

            assertThat(done.get(), @is(false));

            state.set(ONLINE);
            assertEventually("Procedure did not return after index was online", done.get, @is(true), TIMEOUT, _timeUnit);
        }
Exemplo n.º 10
0
            protected internal override IndexStorageFactory buildIndexStorageFactory(FileSystemAbstraction fileSystem, DirectoryFactory directoryFactory)
            {
                FaultyIndexStorageFactory storageFactory = new FaultyIndexStorageFactory(_outerInstance, _faultyIndexId, _error, directoryFactory, directoryStructure());

                _reference.set(storageFactory);
                return(storageFactory);
            }
Exemplo n.º 11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void createANode(java.util.concurrent.atomic.AtomicReference<org.neo4j.graphdb.Node> node) throws Exception
        private void CreateANode(AtomicReference <Node> node)
        {
            _cluster.coreTx((coreGraphDatabase, transaction) =>
            {
                node.set(coreGraphDatabase.createNode());
                transaction.success();
            });
        }
Exemplo n.º 12
0
 internal virtual void IterationFinished()
 {
     // Create new set to not modify set that readers use concurrently
     ReadersShouldSee = new SortedSet <long>(ReadersShouldSee);
     UpdateRecentlyInsertedData(ReadersShouldSee, UpdatesForNextIteration);
     UpdatesForNextIteration = GenerateUpdatesForNextIteration();
     UpdateWithSoonToBeRemovedData(ReadersShouldSee, UpdatesForNextIteration);
     CurrentReaderInstruction.set(NewReaderInstruction(MinRange, MaxRange, ReadersShouldSee));
 }
Exemplo n.º 13
0
        // Timeout as fallback safety if test deadlocks
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 60_000) public void shouldWaitOnStopUntilTheRunningCheckpointIsDone() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldWaitOnStopUntilTheRunningCheckpointIsDone()
        {
            // given
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<Throwable> ex = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <Exception> ex = new AtomicReference <Exception>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean stoppedCompleted = new java.util.concurrent.atomic.AtomicBoolean();
            AtomicBoolean stoppedCompleted = new AtomicBoolean();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch checkPointerLatch = new org.neo4j.test.DoubleLatch(1);
            DoubleLatch checkPointerLatch = new DoubleLatch(1);
            OtherThreadExecutor <Void> otherThreadExecutor = new OtherThreadExecutor <Void>("scheduler stopper", null);
            CheckPointer checkPointer = new CheckPointerAnonymousInnerClass(this, checkPointerLatch);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final CheckPointScheduler scheduler = new CheckPointScheduler(checkPointer, ioLimiter, jobScheduler, 20L, health);
            CheckPointScheduler scheduler = new CheckPointScheduler(checkPointer, _ioLimiter, _jobScheduler, 20L, _health);

            // when
            scheduler.Start();

            Thread runCheckPointer = new Thread(_jobScheduler.runJob);

            runCheckPointer.Start();

            checkPointerLatch.WaitForAllToStart();

            otherThreadExecutor.ExecuteDontWait((OtherThreadExecutor.WorkerCommand <Void, Void>)state =>
            {
                try
                {
                    scheduler.Stop();
                    stoppedCompleted.set(true);
                }
                catch (Exception throwable)
                {
                    ex.set(throwable);
                }
                return(null);
            });
            otherThreadExecutor.WaitUntilWaiting(details => details.isAt(typeof(CheckPointScheduler), "waitOngoingCheckpointCompletion"));

            // then
            assertFalse(stoppedCompleted.get());

            checkPointerLatch.Finish();
            runCheckPointer.Join();

            while (!stoppedCompleted.get())
            {
                Thread.Sleep(1);
            }
            otherThreadExecutor.Dispose();

            assertNull(ex.get());
        }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private Thread newThreadForNodeAction(final long nodeId, final System.Action<org.neo4j.graphdb.Node> nodeConsumer)
        private Thread NewThreadForNodeAction(long nodeId, System.Action <Node> nodeConsumer)
        {
            return(new Thread(() =>
            {
                try
                {
                    using (Transaction tx = _db.beginTx())
                    {
                        Node node = _db.getNodeById(nodeId);
                        _barrier.await();
                        nodeConsumer(node);
                        tx.success();
                    }
                }
                catch (Exception e)
                {
                    _ex.set(e);
                }
            }));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeOut = 5000) public void interruptHangingResultsListener() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void interruptHangingResultsListener()
        {
            HangingFunction     fn   = new HangingFunction();
            CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL);
            CalculationTask     task = CalculationTask.of(TARGET, fn, cell);
            Column           column  = Column.of(TestingMeasures.PRESENT_VALUE);
            CalculationTasks tasks   = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column));

            ExecutorService executor = Executors.newSingleThreadExecutor();

            try
            {
                CalculationTaskRunner test       = CalculationTaskRunner.of(executor);
                MarketData            marketData = MarketData.empty(VAL_DATE);

                AtomicBoolean shouldNeverComplete    = new AtomicBoolean();
                AtomicBoolean interrupted            = new AtomicBoolean();
                AtomicReference <Exception> thrown   = new AtomicReference <Exception>();
                ResultsListener             listener = new ResultsListener();
                test.calculateAsync(tasks, marketData, REF_DATA, listener);
                System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
                Thread thread = new Thread(() =>
                {
                    try
                    {
                        listener.result();
                        shouldNeverComplete.set(true);
                    }
                    catch (Exception ex)
                    {
                        interrupted.set(Thread.CurrentThread.Interrupted);
                        thrown.set(ex);
                    }
                    latch.Signal();
                });
                // run the thread, wait until properly started, then interrupt, wait until properly handled
                thread.Start();
                while (!fn.started)
                {
                }
                thread.Interrupt();
                latch.await();
                // asserts
                assertEquals(interrupted.get(), true);
                assertEquals(shouldNeverComplete.get(), false);
                assertEquals(thrown.get() is Exception, true);
                assertEquals(thrown.get().Cause is InterruptedException, true);
            }
            finally
            {
                executor.shutdownNow();
            }
        }
Exemplo n.º 16
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();
                }
            }));
        }
Exemplo n.º 17
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private javax.ws.rs.core.Response.ResponseBuilder mockResponseBuilder(javax.ws.rs.core.Response response, final java.util.concurrent.atomic.AtomicReference<javax.ws.rs.core.StreamingOutput> ref)
        private Response.ResponseBuilder MockResponseBuilder(Response response, AtomicReference <StreamingOutput> @ref)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.ws.rs.core.Response.ResponseBuilder responseBuilder = mock(javax.ws.rs.core.Response.ResponseBuilder.class);
            Response.ResponseBuilder responseBuilder = mock(typeof(Response.ResponseBuilder));
            when(responseBuilder.entity(ArgumentMatchers.isA(typeof(StreamingOutput)))).thenAnswer(invocationOnMock =>
            {
                @ref.set(invocationOnMock.getArgument(0));
                return(responseBuilder);
            });
            when(responseBuilder.type(ArgumentMatchers.any <MediaType>())).thenReturn(responseBuilder);
            when(responseBuilder.build()).thenReturn(response);
            return(responseBuilder);
        }
Exemplo n.º 18
0
        public override void closeSelf()
        {
            PackList packs = _packList.get();

            _packList.set(NoPacks);
            foreach (PackFile p in packs.packs)
            {
                p.Dispose();
            }

#if DEBUG
            GC.SuppressFinalize(this); // Disarm lock-release checker
#endif
        }
        //-------------------------------------------------------------------------
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeOut = 5000) public void interruptHangingCalculate() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void interruptHangingCalculate()
        {
            HangingFunction     fn   = new HangingFunction();
            CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL);
            CalculationTask     task = CalculationTask.of(TARGET, fn, cell);
            Column           column  = Column.of(TestingMeasures.PRESENT_VALUE);
            CalculationTasks tasks   = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column));

            // using the direct executor means there is no need to close/shutdown the runner
            CalculationTaskRunner test       = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService());
            MarketData            marketData = MarketData.empty(VAL_DATE);

            AtomicBoolean             shouldNeverThrow = new AtomicBoolean();
            AtomicBoolean             interrupted      = new AtomicBoolean();
            AtomicReference <Results> results          = new AtomicReference <Results>();

            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            Thread thread = new Thread(() =>
            {
                try
                {
                    Results result = test.calculate(tasks, marketData, REF_DATA);
                    interrupted.set(Thread.CurrentThread.Interrupted);
                    results.set(result);
                }
                catch (Exception)
                {
                    shouldNeverThrow.set(true);
                }
                latch.Signal();
            });

            // run the thread, wait until properly started, then interrupt, wait until properly handled
            thread.Start();
            while (!fn.started)
            {
            }
            thread.Interrupt();
            latch.await();
            // asserts
            assertEquals(interrupted.get(), true);
            assertEquals(shouldNeverThrow.get(), false);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result00 = results.get().get(0, 0);
            Result <object> result00 = results.get().get(0, 0);

            assertEquals(result00.Failure, true);
            assertEquals(result00.Failure.Reason, FailureReason.CALCULATION_FAILED);
            assertEquals(result00.Failure.Message.Contains("Runtime interrupted"), true);
        }
Exemplo n.º 20
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldUpdateGroupsOnStart() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
		 public virtual void ShouldUpdateGroupsOnStart()
		 {
			  AtomicReference<string> suffix = new AtomicReference<string>( "before" );
			  IList<IList<string>> expected;

			  IDictionary<string, System.Func<int, string>> instanceCoreParams = new Dictionary<string, System.Func<int, string>>();
			  instanceCoreParams[CausalClusteringSettings.server_groups.name()] = id => string.join(", ", MakeCoreGroups(suffix.get(), id));

			  IDictionary<string, System.Func<int, string>> instanceReplicaParams = new Dictionary<string, System.Func<int, string>>();
			  instanceReplicaParams[CausalClusteringSettings.server_groups.name()] = id => string.join(", ", MakeReplicaGroups(suffix.get(), id));

			  int nServers = 3;
			  _cluster = new EnterpriseCluster( TestDir.directory( "cluster" ), nServers, nServers, new HazelcastDiscoveryServiceFactory(), emptyMap(), instanceCoreParams, emptyMap(), instanceReplicaParams, Standard.LATEST_NAME, IpFamily.IPV4, false );

			  // when
			  _cluster.start();

			  // then
			  expected = new List<IList<string>>();
			  foreach ( CoreClusterMember core in _cluster.coreMembers() )
			  {
					expected.Add( MakeCoreGroups( suffix.get(), core.ServerId() ) );
					expected.Add( MakeReplicaGroups( suffix.get(), core.ServerId() ) );
			  }

			  foreach ( CoreClusterMember core in _cluster.coreMembers() )
			  {
					assertEventually( core + " should have groups", () => GetServerGroups(core.Database()), new GroupsMatcher(this, expected), 30, SECONDS );
			  }

			  // when
			  expected.Remove( MakeCoreGroups( suffix.get(), 1 ) );
			  expected.Remove( MakeReplicaGroups( suffix.get(), 2 ) );
			  _cluster.getCoreMemberById( 1 ).shutdown();
			  _cluster.getReadReplicaById( 2 ).shutdown();

			  suffix.set( "after" ); // should update groups of restarted servers
			  _cluster.addCoreMemberWithId( 1 ).start();
			  _cluster.addReadReplicaWithId( 2 ).start();
			  expected.Add( MakeCoreGroups( suffix.get(), 1 ) );
			  expected.Add( MakeReplicaGroups( suffix.get(), 2 ) );

			  // then
			  foreach ( CoreClusterMember core in _cluster.coreMembers() )
			  {
					assertEventually( core + " should have groups", () => GetServerGroups(core.Database()), new GroupsMatcher(this, expected), 30, SECONDS );
			  }
		 }
Exemplo n.º 21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 5000) public void shouldWaitOnStopUntilTheRunningCheckpointIsDone() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldWaitOnStopUntilTheRunningCheckpointIsDone()
        {
            // given
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<Throwable> ex = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <Exception> ex = new AtomicReference <Exception>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch checkPointerLatch = new org.neo4j.test.DoubleLatch(1);
            DoubleLatch   checkPointerLatch = new DoubleLatch(1);
            RaftLogPruner logPruner         = new RaftLogPrunerAnonymousInnerClass(this, Clock.systemUTC(), checkPointerLatch);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final PruningScheduler scheduler = new PruningScheduler(logPruner, jobScheduler, 20L, org.neo4j.logging.NullLogProvider.getInstance());
            PruningScheduler scheduler = new PruningScheduler(logPruner, _jobScheduler, 20L, NullLogProvider.Instance);

            // when
            scheduler.Start();

            Thread runCheckPointer = new Thread(_jobScheduler.runJob);

            runCheckPointer.Start();

            checkPointerLatch.WaitForAllToStart();

            Thread stopper = new Thread(() =>
            {
                try
                {
                    scheduler.Stop();
                }
                catch (Exception throwable)
                {
                    ex.set(throwable);
                }
            });

            stopper.Start();

            checkPointerLatch.Finish();
            runCheckPointer.Join();

            stopper.Join();

            assertNull(ex.get());
        }
Exemplo n.º 22
0
            public override void Run()
            {
                try
                {
                    ReaderReadySignal.Signal();                             // Ready, set...
                    ReaderStartSignal.await();                              // GO!

                    while (!EndSignal.get() && !FailHalt.get())
                    {
                        DoRead();
                    }
                }
                catch (Exception e)
                {
                    ReaderError.set(e);
                    FailHalt.set(true);
                }
            }
Exemplo n.º 23
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void verifyFormat(java.io.File storeFile) throws FormatViolationException, java.io.IOException
        protected internal override void VerifyFormat(File storeFile)
        {
            AtomicReference <FormatViolationException> exception = new AtomicReference <FormatViolationException>();

            WithCursor(storeFile, false, c =>
            {
                int major            = c.Int;
                int minor            = c.Int;
                GenericLayout layout = Layout;
                if (major != layout.MajorVersion() || minor != layout.MinorVersion())
                {
                    exception.set(new FormatViolationException(this, string.Format("Read format version {0:D}.{1:D}, but layout has version {2:D}.{3:D}", major, minor, layout.MajorVersion(), layout.MinorVersion())));
                }
            });
            if (exception.get() != null)
            {
                throw exception.get();
            }
        }
Exemplo n.º 24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldAwaitCompletionOfAllTasks() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void ShouldAwaitCompletionOfAllTasks()
        {
            // given
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final TaskCoordinator coordinator = new TaskCoordinator(1, java.util.concurrent.TimeUnit.MILLISECONDS);
            TaskCoordinator coordinator = new TaskCoordinator(1, TimeUnit.MILLISECONDS);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<String> state = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <string> state = new AtomicReference <string>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<String> states = new java.util.ArrayList<>();
            IList <string> states = new List <string>();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.Barrier_Control phaseA = new org.neo4j.test.Barrier_Control();
            Org.Neo4j.Test.Barrier_Control phaseA = new Org.Neo4j.Test.Barrier_Control();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.Barrier_Control phaseB = new org.neo4j.test.Barrier_Control();
            Org.Neo4j.Test.Barrier_Control phaseB = new Org.Neo4j.Test.Barrier_Control();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.Barrier_Control phaseC = new org.neo4j.test.Barrier_Control();
            Org.Neo4j.Test.Barrier_Control phaseC = new Org.Neo4j.Test.Barrier_Control();

            state.set("A");
            new Thread("awaitCompletion" () =>
            {
                try
                {
                    states.Add(state.get());                         // expects A
                    phaseA.Reached();
                    states.Add(state.get());                         // expects B
                    phaseB.Await();
                    phaseB.Release();
                    coordinator.AwaitCompletion();
                    states.Add(state.get());                         // expects C
                    phaseC.Reached();
                }
                catch (InterruptedException e)
                {
                    Console.WriteLine(e.ToString());
                    Console.Write(e.StackTrace);
                }
            });
Exemplo n.º 25
0
 private ThreadStart CheckpointThread(AtomicBoolean endSignal, AtomicReference <Exception> readerError, AtomicBoolean failHalt)
 {
     return(() =>
     {
         while (!endSignal.get())
         {
             try
             {
                 _index.checkpoint(IOLimiter.UNLIMITED);
                 // Sleep a little in between checkpoints
                 MILLISECONDS.sleep(20L);
             }
             catch (Exception e)
             {
                 readerError.set(e);
                 failHalt.set(true);
             }
         }
     });
 }
Exemplo n.º 26
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void takeOrAwaitLatchMustAwaitExistingLatchAndReturnNull() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void TakeOrAwaitLatchMustAwaitExistingLatchAndReturnNull()
        {
            AtomicReference <Thread> threadRef = new AtomicReference <Thread>();
            BinaryLatch latch = _latches.takeOrAwaitLatch(42);

            assertThat(latch, @is(notNullValue()));
            ExecutorService      executor = Executors.newSingleThreadExecutor();
            Future <BinaryLatch> future   = executor.submit(() =>
            {
                threadRef.set(Thread.CurrentThread);
                return(_latches.takeOrAwaitLatch(42));
            });
            Thread th;

            do
            {
                th = threadRef.get();
            } while (th == null);
            ThreadTestUtils.awaitThreadState(th, 10_000, Thread.State.WAITING);
            latch.Release();
            assertThat(future.get(1, TimeUnit.SECONDS), @is(nullValue()));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT) public void closeWaitForForceToComplete() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CloseWaitForForceToComplete()
        {
            // GIVEN
            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            AtomicReference <Thread>        actionThreadReference = new AtomicReference <Thread>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexProxy inner = new IndexProxyAdapter()
            IndexProxy inner        = new IndexProxyAdapterAnonymousInnerClass4(this, latch, actionThreadReference);
            IndexProxy outer        = NewContractCheckingIndexProxy(inner);
            Thread     actionThread = CreateActionThread(outer.close);

            actionThreadReference.set(actionThread);

            outer.Start();
            Thread thread = RunInSeparateThread(() => outer.force(Org.Neo4j.Io.pagecache.IOLimiter_Fields.Unlimited));

            ThreadTestUtils.awaitThreadState(actionThread, TEST_TIMEOUT, Thread.State.TIMED_WAITING);
            latch.Signal();

            thread.Join();
            actionThread.Join();
        }
Exemplo n.º 28
0
 public void enteredCluster(ClusterConfiguration clusterConfiguration)
 {
     Logger.Logger.fine(_uri + " entered cluster:" + clusterConfiguration.MemberURIs);
     _config.set(new ClusterConfiguration(clusterConfiguration));
     @in.Add(_cluster);
 }
Exemplo n.º 29
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void flushAndForce(org.neo4j.io.pagecache.IOLimiter limiter) throws java.io.IOException
            public override void flushAndForce(IOLimiter limiter)
            {
                base.flushAndForce(limiter);
                _observedLimiter.set(limiter);
            }
Exemplo n.º 30
0
        /*
         * Tests that changes performed in a transaction before commit are not apparent in another.
         */
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testSimpleTransactionIsolation() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TestSimpleTransactionIsolation()
        {
            // Start setup - create base data
            Commit();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch1 = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent latch1 = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch2 = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent latch2 = new System.Threading.CountdownEvent(1);
            Node         n1;
            Node         n2;
            Relationship r1;

            using (Transaction tx = GraphDb.beginTx())
            {
                n1 = GraphDb.createNode();
                n2 = GraphDb.createNode();
                r1 = n1.CreateRelationshipTo(n2, RelationshipType.withName("TEST"));
                tx.Success();
            }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.graphdb.Node node1 = n1;
            Node node1 = n1;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.graphdb.Node node2 = n2;
            Node node2 = n2;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.graphdb.Relationship rel1 = r1;
            Relationship rel1 = r1;

            using (Transaction tx = GraphDb.beginTx())
            {
                node1.SetProperty("key", "old");
                rel1.SetProperty("key", "old");
                tx.Success();
            }
            AssertPropertyEqual(node1, "key", "old");
            AssertPropertyEqual(rel1, "key", "old");
            AssertRelationshipCount(node1, 1);
            AssertRelationshipCount(node2, 1);

            // This is the mutating transaction - it will change stuff which will be read in between
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<Exception> t1Exception = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <Exception> t1Exception = new AtomicReference <Exception>();
            Thread t1 = new Thread(() =>
            {
                try
                {
                    using (Transaction tx = GraphDb.beginTx())
                    {
                        node1.SetProperty("key", "new");
                        rel1.SetProperty("key", "new");
                        node1.CreateRelationshipTo(node2, RelationshipType.withName("TEST"));
                        AssertPropertyEqual(node1, "key", "new");
                        AssertPropertyEqual(rel1, "key", "new");
                        AssertRelationshipCount(node1, 2);
                        AssertRelationshipCount(node2, 2);
                        latch1.Signal();
                        latch2.await();
                        AssertPropertyEqual(node1, "key", "new");
                        AssertPropertyEqual(rel1, "key", "new");
                        AssertRelationshipCount(node1, 2);
                        AssertRelationshipCount(node2, 2);
                        // no tx.success();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    Console.Write(e.StackTrace);
                    Thread.interrupted();
                    t1Exception.set(e);
                }
                finally
                {
                    try
                    {
                        AssertPropertyEqual(node1, "key", "old");
                        AssertPropertyEqual(rel1, "key", "old");
                        AssertRelationshipCount(node1, 1);
                        AssertRelationshipCount(node2, 1);
                    }
                    catch (Exception e)
                    {
                        t1Exception.compareAndSet(null, e);
                    }
                }
            });

            t1.Start();

            latch1.await();

            // The transaction started above that runs in t1 has not finished. The old values should still be visible.
            AssertPropertyEqual(node1, "key", "old");
            AssertPropertyEqual(rel1, "key", "old");
            AssertRelationshipCount(node1, 1);
            AssertRelationshipCount(node2, 1);

            latch2.Signal();
            t1.Join();

            // The transaction in t1 has finished but not committed. Its changes should still not be visible.
            AssertPropertyEqual(node1, "key", "old");
            AssertPropertyEqual(rel1, "key", "old");
            AssertRelationshipCount(node1, 1);
            AssertRelationshipCount(node2, 1);

            if (t1Exception.get() != null)
            {
                throw t1Exception.get();
            }

            using (Transaction tx = GraphDb.beginTx())
            {
                foreach (Relationship rel in node1.Relationships)
                {
                    rel.Delete();
                }
                node1.Delete();
                node2.Delete();
                tx.Success();
            }
        }