//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAllowConcurrentCreationOfNonConflictingData() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldAllowConcurrentCreationOfNonConflictingData() { // given Database.executeAndCommit(CreateUniquenessConstraint("Label1", "key1")); // when Future <bool> created = Database.executeAndCommit(db => { Db.createNode(label("Label1")).setProperty("key1", "value1"); return(OtherThread.execute(CreateNode(db, "Label1", "key1", "value2"))); }); // then assertTrue("Node creation should succeed", created.get()); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReturnCorrectStatusCodeOnDeadlock() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldReturnCorrectStatusCodeOnDeadlock() { // Given using (Transaction tx = Graphdb().beginTx()) { Graphdb().createNode(Label.label("First")); Graphdb().createNode(Label.label("Second")); tx.Success(); } // When I lock node:First HTTP.Response begin = _http.POST("db/data/transaction", quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:First) SET n.prop=1' } ] }")); // and I lock node:Second, and wait for a lock on node:First in another transaction OtherThread.execute(WriteToFirstAndSecond()); // and I wait for those locks to be pending assertTrue(_secondNodeLocked.await(10, TimeUnit.SECONDS)); Thread.Sleep(1000); // and I then try and lock node:Second in the first transaction HTTP.Response deadlock = _http.POST(begin.Location(), quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }")); // Then assertThat(deadlock.Get("errors").get(0).get("code").TextValue, equalTo(DeadlockDetected.code().serialize())); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldHaveTaskQueueSizeEqualToMaxNumberOfProcessors() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldHaveTaskQueueSizeEqualToMaxNumberOfProcessors() { // GIVEN StageControl control = mock(typeof(StageControl)); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); const int processors = 2; int maxProcessors = 5; Configuration configuration = new ConfigurationAnonymousInnerClass(this, maxProcessors); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ProcessorStep<Void> step = new BlockingProcessorStep(control, configuration, processors, latch); ProcessorStep <Void> step = new BlockingProcessorStep(control, configuration, processors, latch); step.Start(ORDER_SEND_DOWNSTREAM); step.Processors(1); // now at 2 // adding up to max processors should be fine for (int i = 0; i < processors + maxProcessors; i++) { step.Receive(i, null); } // WHEN Future <Void> receiveFuture = T2.execute(Receive(processors, step)); T2.get().waitUntilThreadState(Thread.State.TIMED_WAITING); latch.Signal(); // THEN receiveFuture.get(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void sendingButNotReceivingClientShouldBeKilledWhenWriteThrottleMaxDurationIsReached() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void SendingButNotReceivingClientShouldBeKilledWhenWriteThrottleMaxDurationIsReached() { int numberOfRunDiscardPairs = 10_000; string largeString = StringUtils.repeat(" ", 8 * 1024); _client.connect(_address).send(_util.acceptedVersions(1, 0, 0, 0)).send(_util.chunk(new InitMessage("TestClient/1.1", emptyMap()))); assertThat(_client, eventuallyReceives(new sbyte[] { 0, 0, 0, 1 })); assertThat(_client, _util.eventuallyReceives(msgSuccess())); Future sender = OtherThread.execute(state => { for (int i = 0; i < numberOfRunDiscardPairs; i++) { _client.send(_util.chunk(new RunMessage("RETURN $data as data", ValueUtils.asMapValue(singletonMap("data", largeString))), PullAllMessage.INSTANCE)); } return(null); }); try { OtherThread.get().awaitFuture(sender); fail("should throw ExecutionException instead"); } catch (ExecutionException e) { assertThat(Exceptions.rootCause(e), instanceOf(typeof(SocketException))); } _logProvider.assertAtLeastOnce(inLog(Matchers.containsString(typeof(BoltConnection).Assembly.GetName().Name)).error(startsWith("Unexpected error detected in bolt session"), hasProperty("cause", matchesExceptionMessage(containsString("will be closed because the client did not consume outgoing buffers for "))))); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT) public void readOwnChangesFromRacingIndexNoBlock() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ReadOwnChangesFromRacingIndexNoBlock() { Future <Void> t2Future = T2.execute(state => { using (Transaction tx = _db.beginTx()) { CreateNodeWithProperty(_label, PROPERTY_KEY, VALUE_1); AssertNodeWith(_label, PROPERTY_KEY, VALUE_1); tx.success(); } return(null); }); Future <Void> t3Future = T3.execute(state => { using (Transaction tx = _db.beginTx()) { CreateAndAwaitIndex(_label, PROPERTY_KEY); tx.success(); } return(null); }); t3Future.get(); t2Future.get(); AssertInTxNodeWith(_label, PROPERTY_KEY, VALUE_1); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = 10_000) public void shouldWaitForCompletionInHalt() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldWaitForCompletionInHalt() { // GIVEN PageCache pageCache = mock(typeof(PageCache)); Org.Neo4j.Test.Barrier_Control barrier = new Org.Neo4j.Test.Barrier_Control(); doAnswer(invocation => { barrier.Reached(); return(null); }).when(pageCache).flushAndForce(); PageCacheFlusher flusher = new PageCacheFlusher(pageCache); flusher.Start(); // WHEN barrier.Await(); Future <object> halt = T2.execute(state => { flusher.Halt(); return(null); }); T2.get().waitUntilWaiting(details => details.isAt(typeof(PageCacheFlusher), "halt")); barrier.Release(); // THEN halt call exits normally after (confirmed) ongoing flushAndForce call completed. halt.get(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT) public void firstRemoveSecondChangeProperty() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void FirstRemoveSecondChangeProperty() { // GIVEN //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.test.Barrier_Control barrier = new org.neo4j.test.Barrier_Control(); Org.Neo4j.Test.Barrier_Control barrier = new Org.Neo4j.Test.Barrier_Control(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Node node; Node node; using (Transaction tx = _db.beginTx()) { node = _db.createNode(); node.SetProperty(PROPERTY_KEY, VALUE_1); tx.Success(); } // WHEN Future <Void> future = T2.execute(state => { using (Transaction tx = _db.beginTx()) { node.RemoveProperty(PROPERTY_KEY); tx.Success(); barrier.Reached(); } return(null); }); using (Transaction tx = _db.beginTx()) { barrier.Await(); node.SetProperty(PROPERTY_KEY, VALUE_2); tx.Success(); barrier.Release(); } future.get(); using (Transaction tx = _db.beginTx()) { assertEquals(VALUE_2, node.GetProperty(PROPERTY_KEY, VALUE_2)); tx.Success(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void recoverFromConstraintAppliedBeforeCrash(System.Action<org.neo4j.kernel.internal.GraphDatabaseAPI> constraintCreator) throws Exception private void RecoverFromConstraintAppliedBeforeCrash(System.Action <GraphDatabaseAPI> constraintCreator) { IList <TransactionRepresentation> transactions = CreateTransactionsForCreatingConstraint(constraintCreator); EphemeralFileSystemAbstraction crashSnapshot; { GraphDatabaseAPI db = NewDb(); Org.Neo4j.Test.Barrier_Control barrier = new Org.Neo4j.Test.Barrier_Control(); _monitors.addMonitorListener(new MonitorAdapterAnonymousInnerClass(this, barrier)); try { // Create two nodes that have duplicate property values string value = "v"; using (Transaction tx = Db.beginTx()) { for (int i = 0; i < 2; i++) { Db.createNode(LABEL).setProperty(KEY, value); } tx.Success(); } T2.execute(state => { Apply(db, transactions.subList(0, transactions.Count - 1)); return(null); }); barrier.Await(); FlushStores(db); // Crash before index population have discovered that there are duplicates // (nowadays happens in between index population and creating the constraint) crashSnapshot = Fs.snapshot(); barrier.Release(); } finally { Db.shutdown(); } } { // WHEN GraphDatabaseAPI db = ( GraphDatabaseAPI )(new TestEnterpriseGraphDatabaseFactory()).setFileSystem(crashSnapshot).newImpermanentDatabase(); try { Recreate(constraintCreator).accept(db, transactions); fail("Should not be able to create constraint on non-unique data"); } catch (Exception e) when(e is ConstraintViolationException || e is QueryExecutionException) { // THEN good } finally { Db.shutdown(); } } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void givenDatabaseAndStartedTxWhenShutdownThenWaitForTxToFinish() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void GivenDatabaseAndStartedTxWhenShutdownThenWaitForTxToFinish() { // Given //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final GraphDatabaseService db = getTemporaryDatabase(); GraphDatabaseService db = TemporaryDatabase; // When Org.Neo4j.Test.Barrier_Control barrier = new Org.Neo4j.Test.Barrier_Control(); Future <object> txFuture = _t2.execute(state => { using (Transaction tx = Db.beginTx()) { barrier.Reached(); Db.createNode(); tx.Success(); } return(null); }); // i.e. wait for transaction to start barrier.Await(); // now there's a transaction open, blocked on continueTxSignal Future <object> shutdownFuture = _t3.execute(state => { Db.shutdown(); return(null); }); _t3.get().waitUntilWaiting(location => location.isAt(typeof(DatabaseAvailability), "stop")); barrier.Release(); try { txFuture.get(); } catch (ExecutionException) { // expected } shutdownFuture.get(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void assertRelsInSeparateTx(final long refNode, final org.neo4j.graphdb.Direction both, final long... longs) throws InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException //JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected: private void AssertRelsInSeparateTx(long refNode, Direction both, params long[] longs) { assertTrue(OtherThread.execute(state => { using (Transaction ktx = Kernel.beginTransaction(@implicit, LoginContext.AUTH_DISABLED)) { AssertRels(NodeGetRelationships(ktx, refNode, both), longs); } return(true); }).get(10, TimeUnit.SECONDS)); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void shouldNotAllowConstraintsViolationsUnderStress(Operation ops) throws Exception private void ShouldNotAllowConstraintsViolationsUnderStress(Operation ops) { // Given HighlyAvailableGraphDatabase master = Cluster.Master; HighlyAvailableGraphDatabase slave = Cluster.AnySlave; // Because this is a brute-force test, we run for a user-specified time, and consider ourselves successful if // no failure is found. long end = DateTimeHelper.CurrentUnixTimeMillis() + _runtime; int successfulAttempts = 0; while (end > DateTimeHelper.CurrentUnixTimeMillis()) { // Each round of this loop: // - on a slave, creates a set of nodes with a label/property combo with all-unique values // - on the master, creates a property constraint // - on a slave, while the master is creating the constraint, starts transactions that will // violate the constraint { //setup : // Set a target property for the constraint for this round SetLabelAndPropertyForNextRound(); // Ensure slave has constraints from previous round Cluster.sync(); // Create the initial data that *does not* violate the constraint try { SlaveWork.execute(PerformConstraintCompliantInserts(slave)).get(); } catch (ExecutionException e) { if (Exceptions.contains(e, "could not connect", typeof(ComException))) { // We're in a weird cluster state. The slave should be able to succeed if trying again continue; } } } { //stress : ops.Perform(); // And then ensure all is well AssertConstraintsNotViolated(ops.ConstraintCreation, ops.ConstraintViolation, master); successfulAttempts++; } } assertThat(successfulAttempts, greaterThan(0)); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void assertBlock(Runnable runLock, Runnable runUnlock) throws Exception private void AssertBlock(ThreadStart runLock, ThreadStart runUnlock) { Future <object> future = Executor.execute(state => { runLock.run(); return(null); }); Executor.get().waitUntilWaiting(details => details.isAt(typeof(GBPTreeLock), "doLock")); runUnlock.run(); future.get(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = 60000) public void deadlockShouldRollbackTransaction() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void DeadlockShouldRollbackTransaction() { // Given HTTP.Response initial = POST(TxCommitUri(), quotedJson("{'statements': [{'statement': 'CREATE (n1 {prop : 1}), (n2 {prop : 2})'}]}")); assertThat(initial.Status(), @is(200)); assertThat(initial, containsNoErrors()); // When // tx1 takes a write lock on node1 HTTP.Response firstInTx1 = POST(TxUri(), quotedJson("{'statements': [{'statement': 'MATCH (n {prop : 1}) SET n.prop = 3'}]}")); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final long tx1 = extractTxId(firstInTx1); long tx1 = ExtractTxId(firstInTx1); // tx2 takes a write lock on node2 HTTP.Response firstInTx2 = POST(TxUri(), quotedJson("{'statements': [{'statement': 'MATCH (n {prop : 2}) SET n.prop = 4'}]}")); long tx2 = ExtractTxId(firstInTx2); // tx1 attempts to take a write lock on node2 Future <HTTP.Response> future = OtherThread.execute(state => POST(TxUri(tx1), quotedJson("{'statements': [{'statement': 'MATCH (n {prop : 2}) SET n.prop = 5'}]}"))); // tx2 attempts to take a write lock on node1 HTTP.Response secondInTx2 = POST(TxUri(tx2), quotedJson("{'statements': [{'statement': 'MATCH (n {prop : 1}) SET n.prop = 6'}]}")); HTTP.Response secondInTx1 = future.get(); // Then assertThat(secondInTx1.Status(), @is(200)); assertThat(secondInTx2.Status(), @is(200)); // either tx1 or tx2 should fail because of the deadlock HTTP.Response failed; if (ContainsError(secondInTx1)) { failed = secondInTx1; } else if (ContainsError(secondInTx2)) { failed = secondInTx2; } else { failed = null; fail("Either tx1 or tx2 is expected to fail"); } assertThat(failed, hasErrors(Org.Neo4j.Kernel.Api.Exceptions.Status_Transaction.DeadlockDetected)); // transaction was rolled back on the previous step and we can't commit it HTTP.Response commit = POST(failed.StringFromContent("commit")); assertThat(commit.Status(), @is(404)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAllowCreationOfNonConflictingDataOnSeparateHosts() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldAllowCreationOfNonConflictingDataOnSeparateHosts() { // given ClusterManager.ManagedCluster cluster = ClusterRule.startCluster(); HighlyAvailableGraphDatabase slave1 = cluster.AnySlave; HighlyAvailableGraphDatabase slave2 = cluster.GetAnySlave(slave1); // when Future <bool> created; using (Transaction tx = slave1.BeginTx()) { slave1.CreateNode(_label).setProperty(PROPERTY_KEY, "value1"); created = OtherThread.execute(CreateNode(slave2, _label.name(), PROPERTY_KEY, "value2")); tx.Success(); } // then assertTrue("creating non-conflicting data should pass", created.get()); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReadCorrectResultsFromMultipleNestedReadersWhenConcurrentWriteHappens() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldReadCorrectResultsFromMultipleNestedReadersWhenConcurrentWriteHappens() { // given CreateIndex(); using (Transaction tx = Db.beginTx()) { for (int id = 0; id < IDS; id++) { for (int i = 0; i < NODE_PER_ID; i++) { Db.createNode(_label).setProperty(KEY, id); } } tx.Success(); } // when using (Transaction tx = Db.beginTx()) { // opening all the index readers IList <ResourceIterator <Node> > iterators = new List <ResourceIterator <Node> >(); for (int id = 0; id < IDS; id++) { iterators.Add(Db.findNodes(_label, KEY, id)); } // then iterating over them interleaved should yield all the expected results each for (int i = 0; i < NODE_PER_ID; i++) { AssertRoundOfNodes(iterators); if (i % 2 == 1) { // will be triggered on i == 1 T2.execute(NodeCreator()).get(); } } AssertRoundOfNodes(iterators); foreach (ResourceIterator <Node> reader in iterators) { //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: assertFalse(reader.hasNext()); reader.Close(); } tx.Success(); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void throwsWhenTxAwaitDurationExpires() public virtual void ThrowsWhenTxAwaitDurationExpires() { long lastClosedTransactionId = 100; System.Func <TransactionIdStore> txIdStore = () => FixedTxIdStore(lastClosedTransactionId); Duration txAwaitDuration = Duration.ofSeconds(42); FakeClock clock = new FakeClock(); DatabaseAvailabilityGuard databaseAvailabilityGuard = spy(new DatabaseAvailabilityGuard(DEFAULT_DATABASE_NAME, clock, NullLog.Instance)); when(databaseAvailabilityGuard.Available).then(invocation => { // move clock forward on the first availability check // this check is executed on every tx id polling iteration bool available = ( bool )invocation.callRealMethod(); clock.Forward(txAwaitDuration.Seconds + 1, SECONDS); return(available); }); TransactionStateMachineV1SPI txSpi = CreateTxSpi(txIdStore, txAwaitDuration, databaseAvailabilityGuard, clock); Future <Void> result = OtherThread.execute(state => { txSpi.AwaitUpToDate(lastClosedTransactionId + 42); return(null); }); try { result.get(20, SECONDS); } catch (Exception e) { assertThat(e, instanceOf(typeof(ExecutionException))); assertThat(e.InnerException, instanceOf(typeof(TransactionFailureException))); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void processNextBatchShouldReturnWhenConnectionIsStopped() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ProcessNextBatchShouldReturnWhenConnectionIsStopped() { BoltConnection connection = NewConnection(1); connection.Enqueue(Jobs.noop()); connection.Enqueue(Jobs.noop()); // force to a message waiting loop when(_stateMachine.shouldStickOnThread()).thenReturn(true); Future <bool> future = OtherThread.execute(state => connection.ProcessNextBatch()); connection.Stop(); OtherThread.get().awaitFuture(future); verify(_stateMachine).close(); }
private Future <object> ApplyInT2(GraphDatabaseAPI db, IList <TransactionRepresentation> transactions) { TransactionCommitProcess commitProcess = Db.DependencyResolver.resolveDependency(typeof(TransactionCommitProcess)); return(T2.execute(state => { transactions.ForEach(tx => { try { // It will matter if the transactions are supplied all in the same batch or one by one // since the CountsTracker#apply lock is held and released per transaction commitProcess.Commit(new TransactionToApply(tx), NULL, EXTERNAL); } catch (TransactionFailureException e) { throw new Exception(e); } }); return null; })); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void setUp() throws InterruptedException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void SetUp() { _executor = Executors.newCachedThreadPool(); _startLogRotationLatch = new System.Threading.CountdownEvent(1); _completeLogRotationLatch = new System.Threading.CountdownEvent(1); _writerStopped = new AtomicBoolean(); _monitors = Db.DependencyResolver.resolveDependency(typeof(Monitors)); _rotationListener = new LogRotation_MonitorAnonymousInnerClass(this); _monitors.addMonitorListener(_rotationListener); _label = Label.label("Label"); _rotationFuture = T2.execute(ForceLogRotation(db)); // Waiting for the writer task to start a log rotation _startLogRotationLatch.await(); // Then we should be able to start a transaction, though perhaps not be able to finish it. // This is what the individual test methods will be doing. // The test passes when transaction.close completes within the test timeout, that is, it didn't deadlock. }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotSeeFreedIdsCrossRoleSwitch() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldNotSeeFreedIdsCrossRoleSwitch() { // GIVEN ManagedCluster cluster = ClusterRule.startCluster(); HighlyAvailableGraphDatabase firstMaster = cluster.Master; // WHEN // a node with a property Node node = CreateNodeWithProperties(firstMaster, 1); // sync cluster cluster.Sync(); // a transaction on master which deletes the property DeleteNode(node, firstMaster); TriggerIdMaintenance(firstMaster); CreateNodeWithProperties(firstMaster, 1); // <-- this one reuses the same property id 0 // a transaction T on slave which will be kept open using a barrier GraphDatabaseAPI slave = cluster.AnySlave; Org.Neo4j.Test.Barrier_Control barrier = new Org.Neo4j.Test.Barrier_Control(); Future <Void> t = T2.execute(BarrierControlledReadTransaction(slave, barrier)); // pull updates on slave barrier.Await(); slave.DependencyResolver.resolveDependency(typeof(UpdatePuller)).pullUpdates(); // a role switch cluster.Shutdown(firstMaster); cluster.Await(masterAvailable(firstMaster)); // close T barrier.Release(); t.get(); TriggerIdMaintenance(slave); // THEN the deleted property record should now not be in freelist on new master CreateNodeWithProperties(slave, 10); // <-- this transaction should introduce inconsistencies cluster.Stop(); // <-- CC will be run here since that's configured above ^^^ }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotDeadlock() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldNotDeadlock() { IList <TransactionRepresentation> transactions = CreateConstraintCreatingTransactions(); Monitors monitors = new Monitors(); GraphDatabaseAPI db = ( GraphDatabaseAPI )(new TestGraphDatabaseFactory()).setMonitors(monitors).newImpermanentDatabase(); Org.Neo4j.Test.Barrier_Control controller = new Org.Neo4j.Test.Barrier_Control(); bool success = false; try { IndexingService.Monitor monitor = new MonitorAdapterAnonymousInnerClass(this, controller); monitors.AddMonitorListener(monitor); Future <object> applier = ApplyInT2(db, transactions); controller.Await(); // At this point the index population has completed and the population thread is ready to // acquire the counts store read lock for initializing some samples there. We're starting the // check pointer, which will eventually put itself in queue for acquiring the write lock Future <object> checkPointer = T3.execute(state => Db.DependencyResolver.resolveDependency(typeof(CheckPointer)).forceCheckPoint(new SimpleTriggerInfo("MANUAL"))); try { T3.get().waitUntilWaiting(details => details.isAt(typeof(LockWrapper), "writeLock")); } catch (System.InvalidOperationException) { // Thrown when the fix is in, basically it's thrown if the check pointer didn't get blocked checkPointer.get(); // to assert that no exception was thrown during in check point thread } // Alright the trap is set. Let the population thread move on and seal the deal controller.Release(); // THEN these should complete applier.get(10, SECONDS); checkPointer.get(10, SECONDS); success = true; using (Transaction tx = Db.beginTx()) { ConstraintDefinition constraint = single(Db.schema().getConstraints(LABEL)); assertEquals(KEY, single(constraint.PropertyKeys)); tx.Success(); } CreateNode(db, "A"); try { CreateNode(db, "A"); fail("Should have failed"); } catch (ConstraintViolationException) { // THEN good } } finally { if (!success) { T2.interrupt(); T3.interrupt(); // so that shutdown won't hang too } Db.shutdown(); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldBeAbleToShutdownWhenThereAreTransactionsWaitingForLocks() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldBeAbleToShutdownWhenThereAreTransactionsWaitingForLocks() { // GIVEN //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Node node; Node node; using (Transaction tx = _db.beginTx()) { node = _db.createNode(); tx.Success(); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch nodeLockedLatch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent nodeLockedLatch = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch shutdownCalled = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent shutdownCalled = new System.Threading.CountdownEvent(1); // WHEN // one thread locks previously created node and initiates graph db shutdown Future <Void> shutdownFuture = T2.execute(state => { using (Transaction tx = _db.beginTx()) { node.AddLabel(label("ABC")); nodeLockedLatch.Signal(); // Wait for T3 to start waiting for this node write lock T3.get().waitUntilWaiting(details => details.isAt(typeof(CommunityLockClient), "acquireExclusive")); _db.shutdown(); shutdownCalled.Signal(); tx.Success(); } return(null); }); // other thread tries to lock the same node while it has been locked and graph db is being shutdown Future <Void> secondTxResult = T3.execute(state => { using (Transaction tx = _db.beginTx()) { nodeLockedLatch.await(); // T2 awaits this thread to get into a waiting state for this node write lock node.AddLabel(label("DEF")); shutdownCalled.await(); tx.Success(); } return(null); }); // start waiting when the trap has been triggered try { secondTxResult.get(60, SECONDS); fail("Exception expected"); } catch (Exception e) { assertThat(rootCause(e), instanceOf(typeof(TransactionTerminatedException))); } try { shutdownFuture.get(); fail("Should thrown exception since transaction should be canceled."); } catch (Exception e) { assertThat(rootCause(e), instanceOf(typeof(TransactionTerminatedException))); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotSeeEmptyLogFileWhenReadingTransactionStream() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldNotSeeEmptyLogFileWhenReadingTransactionStream() { // GIVEN LogVersionRepository logVersionRepository = new SimpleLogVersionRepository(); LogFiles logFiles = LogFilesBuilder.builder(_directory.databaseLayout(), _fileSystemRule.get()).withLogVersionRepository(logVersionRepository).withTransactionIdStore(new SimpleTransactionIdStore()).build(); _life.add(logFiles); LogFile logFile = logFiles.LogFile; FlushablePositionAwareChannel writer = logFile.Writer; LogPositionMarker startPosition = new LogPositionMarker(); writer.GetCurrentPosition(startPosition); // WHEN AtomicBoolean end = new AtomicBoolean(); sbyte[] dataChunk = new sbyte[100]; // one thread constantly writing to and rotating the channel AtomicInteger rotations = new AtomicInteger(); System.Threading.CountdownEvent startSignal = new System.Threading.CountdownEvent(1); Future <Void> writeFuture = _t2.execute(ignored => { ThreadLocalRandom random = ThreadLocalRandom.current(); startSignal.Signal(); while (!end.get()) { writer.Put(dataChunk, random.Next(1, dataChunk.Length)); if (logFile.RotationNeeded()) { logFile.Rotate(); // Let's just close the gap to the reader so that it gets closer to the "hot zone" // where the rotation happens. writer.GetCurrentPosition(startPosition); rotations.incrementAndGet(); } } return(null); }); assertTrue(startSignal.await(10, SECONDS)); // one thread reading through the channel long maxEndTime = currentTimeMillis() + _limitTime; int reads = 0; try { for ( ; currentTimeMillis() < maxEndTime && reads < LIMIT_READS && rotations.get() < LIMIT_ROTATIONS; reads++) { using (ReadableLogChannel reader = logFile.GetReader(startPosition.NewPosition())) { Deplete(reader); } } } finally { end.set(true); writeFuture.get(); } // THEN simply getting here means this was successful }
public virtual Future <object> Call() { return(Thread.execute(this)); }