コード例 #1
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private <T> T[] getList(String name, org.neo4j.kernel.internal.GraphDatabaseAPI graphDb, Converter<T> converter) throws org.neo4j.server.rest.repr.BadInputException
        private T[] GetList <T>(string name, GraphDatabaseAPI graphDb, Converter <T> converter)
        {
            object value = _data[name];

            if (value == null)
            {
                return(null);
            }
            IList <T> result = new List <T>();

            if (value is object[])
            {
                foreach (object element in ( object[] )value)
                {
                    result.Add(converter.Convert(graphDb, element));
                }
            }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: else if (value instanceof Iterable<?>)
            else if (value is IEnumerable <object> )
            {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (Object element : (Iterable<?>) value)
                foreach (object element in (IEnumerable <object>)value)
                {
                    result.Add(converter.Convert(graphDb, element));
                }
            }
            else
            {
                throw new BadInputException(name + " is not a list");
            }
            return(result.toArray(converter.NewArray(result.Count)));
        }
コード例 #2
0
ファイル: CountsRotationTest.cs プロジェクト: Neo4Net/Neo4Net
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCreateEmptyCountsTrackerStoreWhenCreatingDatabase()
        public virtual void ShouldCreateEmptyCountsTrackerStoreWhenCreatingDatabase()
        {
            // GIVEN
            GraphDatabaseAPI db = ( GraphDatabaseAPI )_dbBuilder.newGraphDatabase();

            // WHEN
            Db.shutdown();

            // THEN
            assertTrue(_fs.fileExists(AlphaStoreFile()));
            assertFalse(_fs.fileExists(BetaStoreFile()));

            using (Lifespan life = new Lifespan())
            {
                CountsTracker store = life.Add(CreateCountsTracker(_pageCache));

                assertEquals(BASE_TX_ID, store.TxId());
                assertEquals(INITIAL_MINOR_VERSION, store.MinorVersion());
                assertEquals(0, store.TotalEntriesStored());
                assertEquals(0, AllRecords(store).Count);
            }

            using (Lifespan life = new Lifespan())
            {
                CountsTracker store = life.Add(CreateCountsTracker(_pageCache));
                assertEquals(BASE_TX_ID, store.TxId());
                assertEquals(INITIAL_MINOR_VERSION, store.MinorVersion());
                assertEquals(0, store.TotalEntriesStored());
                assertEquals(0, AllRecords(store).Count);
            }
        }
コード例 #3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void recoverFirstCorruptedTransactionAfterCheckpointInLastLogFile() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RecoverFirstCorruptedTransactionAfterCheckpointInLastLogFile()
        {
            GraphDatabaseAPI database = ( GraphDatabaseAPI )_databaseFactory.newEmbeddedDatabase(_storeDir);

            GenerateTransactionsAndRotate(database, 5);
            database.Shutdown();

            File highestLogFile     = _logFiles.HighestLogFile;
            long originalFileLength = highestLogFile.length();

            AddCorruptedCommandsToLastLogFile();
            long modifiedFileLength = highestLogFile.length();

            assertThat(modifiedFileLength, greaterThan(originalFileLength));

            database = StartDbNoRecoveryOfCorruptedLogs();
            database.Shutdown();

            _logProvider.rawMessageMatcher().assertContains("Fail to read transaction log version 5.");
            _logProvider.rawMessageMatcher().assertContains("Fail to read first transaction of log version 5.");
            _logProvider.rawMessageMatcher().assertContains("Recovery required from position LogPosition{logVersion=5, byteOffset=593}");
            _logProvider.rawMessageMatcher().assertContains("Fail to recover all transactions. " + "Any later transactions after position LogPosition{logVersion=5, byteOffset=593} " + "are unreadable and will be truncated.");

            assertEquals(5, _logFiles.HighestLogVersion);
            ObjectLongMap <Type> logEntriesDistribution = GetLogEntriesDistribution(_logFiles);

            assertEquals(1, logEntriesDistribution.get(typeof(CheckPoint)));
            assertEquals(originalFileLength, highestLogFile.length());
        }
コード例 #4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRebuildFromLogUpToATx() throws Exception, org.neo4j.consistency.checking.InconsistentStoreException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRebuildFromLogUpToATx()
        {
            // given
            File prototypePath = PrototypePath;
            long txId          = PopulatePrototype(prototypePath);

            File copy = new File(_dir.databaseDir(), "copy");

            FileUtils.copyRecursively(prototypePath, copy);
            GraphDatabaseAPI db = db(copy);

            try
            {
                using (Org.Neo4j.Graphdb.Transaction tx = Db.beginTx())
                {
                    Db.createNode();
                    tx.Success();
                }
            }
            finally
            {
                Db.shutdown();
            }

            // when
            File rebuildPath = RebuilPath;

            (new RebuildFromLogs(_fileSystemRule.get())).rebuild(copy, rebuildPath, txId);

            // then
            assertEquals(GetDbRepresentation(prototypePath), GetDbRepresentation(rebuildPath));
        }
コード例 #5
0
        private void PrepareDbWithDeletedRelationshipPartOfTheChain()
        {
            GraphDatabaseAPI db = ( GraphDatabaseAPI )(new TestGraphDatabaseFactory()).newEmbeddedDatabaseBuilder(_testDirectory.databaseDir()).setConfig(GraphDatabaseSettings.record_format, RecordFormatName).setConfig("dbms.backup.enabled", "false").newGraphDatabase();

            try
            {
                RelationshipType relationshipType = RelationshipType.withName("testRelationshipType");
                using (Transaction tx = Db.beginTx())
                {
                    Node node1 = set(Db.createNode());
                    Node node2 = set(Db.createNode(), property("key", "value"));
                    node1.CreateRelationshipTo(node2, relationshipType);
                    node1.CreateRelationshipTo(node2, relationshipType);
                    node1.CreateRelationshipTo(node2, relationshipType);
                    node1.CreateRelationshipTo(node2, relationshipType);
                    node1.CreateRelationshipTo(node2, relationshipType);
                    node1.CreateRelationshipTo(node2, relationshipType);
                    tx.Success();
                }

                RecordStorageEngine recordStorageEngine = Db.DependencyResolver.resolveDependency(typeof(RecordStorageEngine));

                NeoStores          neoStores          = recordStorageEngine.TestAccessNeoStores();
                RelationshipStore  relationshipStore  = neoStores.RelationshipStore;
                RelationshipRecord relationshipRecord = new RelationshipRecord(-1);
                RelationshipRecord record             = relationshipStore.GetRecord(4, relationshipRecord, RecordLoad.FORCE);
                record.InUse = false;
                relationshipStore.UpdateRecord(relationshipRecord);
            }
            finally
            {
                Db.shutdown();
            }
        }
コード例 #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void nonRecoveredDatabase() throws java.io.IOException
        private void NonRecoveredDatabase()
        {
            File tmpLogDir = new File(_testDirectory.directory(), "logs");

            _fs.mkdir(tmpLogDir);
            File             storeDir = _testDirectory.databaseDir();
            GraphDatabaseAPI db       = ( GraphDatabaseAPI )(new TestGraphDatabaseFactory()).newEmbeddedDatabaseBuilder(storeDir).setConfig(GraphDatabaseSettings.record_format, RecordFormatName).setConfig("dbms.backup.enabled", "false").newGraphDatabase();

            RelationshipType relationshipType = RelationshipType.withName("testRelationshipType");

            using (Transaction tx = Db.beginTx())
            {
                Node node1 = set(Db.createNode());
                Node node2 = set(Db.createNode(), property("key", "value"));
                node1.CreateRelationshipTo(node2, relationshipType);
                tx.Success();
            }
            File[] txLogs = LogFilesBuilder.logFilesBasedOnlyBuilder(storeDir, _fs).build().logFiles();
            foreach (File file in txLogs)
            {
                _fs.copyToDirectory(file, tmpLogDir);
            }
            Db.shutdown();
            foreach (File txLog in txLogs)
            {
                _fs.deleteFile(txLog);
            }

            foreach (File file in LogFilesBuilder.logFilesBasedOnlyBuilder(tmpLogDir, _fs).build().logFiles())
            {
                _fs.moveToDirectory(file, storeDir);
            }
        }
コード例 #7
0
        private static TransactionIdTracker TransactionIdTracker(GraphDatabaseAPI database)
        {
            System.Func <TransactionIdStore> transactionIdStore = database.DependencyResolver.provideDependency(typeof(TransactionIdStore));
            AvailabilityGuard databaseAvailabilityGuard         = database.DependencyResolver.resolveDependency(typeof(DatabaseAvailabilityGuard));

            return(new TransactionIdTracker(transactionIdStore, databaseAvailabilityGuard));
        }
コード例 #8
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected org.neo4j.graphdb.Node convertNode(org.neo4j.kernel.internal.GraphDatabaseAPI graphDb, Object value) throws BadInputException
        protected internal virtual Node ConvertNode(GraphDatabaseAPI graphDb, object value)
        {
            if (value is Node)
            {
                return(( Node )value);
            }
            if (value is URI)
            {
                try
                {
                    return(GetNode(graphDb, ( URI )value));
                }
                catch (NodeNotFoundException e)
                {
                    throw new BadInputException(e);
                }
            }
            if (value is string)
            {
                try
                {
                    return(GetNode(graphDb, ( string )value));
                }
                catch (NodeNotFoundException e)
                {
                    throw new BadInputException(e);
                }
            }
            throw new BadInputException("Could not convert!");
        }
コード例 #9
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected org.neo4j.graphdb.Relationship convertRelationship(org.neo4j.kernel.internal.GraphDatabaseAPI graphDb, Object value) throws BadInputException
        protected internal virtual Relationship ConvertRelationship(GraphDatabaseAPI graphDb, object value)
        {
            if (value is Relationship)
            {
                return(( Relationship )value);
            }
            if (value is URI)
            {
                try
                {
                    return(GetRelationship(graphDb, ( URI )value));
                }
                catch (RelationshipNotFoundException e)
                {
                    throw new BadInputException(e);
                }
            }
            if (value is string)
            {
                try
                {
                    return(GetRelationship(graphDb, ( string )value));
                }
                catch (RelationshipNotFoundException e)
                {
                    throw new BadInputException(e);
                }
            }
            throw new BadInputException("Could not convert!");
        }
コード例 #10
0
ファイル: CountsRotationTest.cs プロジェクト: Neo4Net/Neo4Net
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRotateCountsStoreWhenClosingTheDatabase()
        public virtual void ShouldRotateCountsStoreWhenClosingTheDatabase()
        {
            // GIVEN
            GraphDatabaseAPI db = ( GraphDatabaseAPI )_dbBuilder.newGraphDatabase();

            using (Transaction tx = Db.beginTx())
            {
                Db.createNode(_a);
                tx.Success();
            }

            // WHEN
            Db.shutdown();

            // THEN
            assertTrue(_fs.fileExists(AlphaStoreFile()));
            assertTrue(_fs.fileExists(BetaStoreFile()));

            using (Lifespan life = new Lifespan())
            {
                CountsTracker store = life.Add(CreateCountsTracker(_pageCache));
                // a transaction for creating the label and a transaction for the node
                assertEquals(BASE_TX_ID + 1 + 1, store.TxId());
                assertEquals(INITIAL_MINOR_VERSION, store.MinorVersion());
                // one for all nodes and one for the created "A" label
                assertEquals(1 + 1, store.TotalEntriesStored());
                assertEquals(1 + 1, AllRecords(store).Count);
            }
        }
コード例 #11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void terminateLongRunningRestTransactionalEndpointWithCustomTimeoutQuery() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
		 public virtual void TerminateLongRunningRestTransactionalEndpointWithCustomTimeoutQuery()
		 {
			  GraphDatabaseAPI database = StartDatabaseWithTimeout();
			  KernelTransactionMonitor timeoutMonitor = database.DependencyResolver.resolveDependency( typeof( KernelTransactionMonitor ) );
			  OpenEnterpriseNeoServer neoServer = StartNeoServer( ( GraphDatabaseFacade ) database );
			  long customTimeout = TimeUnit.SECONDS.toMillis( 10 );
			  HTTP.Response beginResponse = HTTP.withHeaders( HttpHeaderUtils.MAX_EXECUTION_TIME_HEADER, customTimeout.ToString() ).POST(TransactionUri(neoServer), quotedJson("{ 'statements': [ { 'statement': 'CREATE (n)' } ] }"));
			  assertEquals( "Response should be successful.", 201, beginResponse.Status() );

			  string transactionEndPoint = beginResponse.Location();
			  _fakeClock.forward( 3, TimeUnit.SECONDS );

			  HTTP.Response response = HTTP.POST( transactionEndPoint, quotedJson( "{ 'statements': [ { 'statement': 'CREATE (n)' } ] }" ) );
			  assertEquals( "Response should be successful.", 200, response.Status() );

			  _fakeClock.forward( 11, TimeUnit.SECONDS );
			  timeoutMonitor.Run();

			  response = HTTP.POST( transactionEndPoint, quotedJson( "{ 'statements': [ { 'statement': 'CREATE (n)' } ] }" ) );
			  assertEquals( "Response should be successful.", 200, response.Status() );

			  HTTP.Response commitResponse = HTTP.POST( transactionEndPoint + "/commit" );
			  assertEquals( "Transaction should be already closed and not found.", 404, commitResponse.Status() );

			  assertEquals( "Transaction should be forcefully closed.", TransactionNotFound.code().serialize(), commitResponse.Get("errors").findValue("code").asText() );
			  AssertDatabaseDoesNotHaveNodes( database );
		 }
コード例 #12
0
        private static TransactionIdTracker NewTransactionIdTracker(GraphDatabaseAPI db)
        {
            System.Func <TransactionIdStore> transactionIdStoreSupplier = Db.DependencyResolver.provideDependency(typeof(TransactionIdStore));
            AvailabilityGuard guard = ResolveDependency(db, typeof(DatabaseAvailabilityGuard));

            return(new TransactionIdTracker(transactionIdStoreSupplier, guard));
        }
コード例 #13
0
        private static TransactionStateMachineV1SPI CreateTxSpi(System.Func <TransactionIdStore> txIdStore, Duration txAwaitDuration, DatabaseAvailabilityGuard availabilityGuard, Clock clock)
        {
            QueryExecutionEngine queryExecutionEngine = mock(typeof(QueryExecutionEngine));

            DependencyResolver             dependencyResolver = mock(typeof(DependencyResolver));
            ThreadToStatementContextBridge bridge             = new ThreadToStatementContextBridge(availabilityGuard);

            when(dependencyResolver.ResolveDependency(typeof(ThreadToStatementContextBridge))).thenReturn(bridge);
            when(dependencyResolver.ResolveDependency(typeof(QueryExecutionEngine))).thenReturn(queryExecutionEngine);
            when(dependencyResolver.ResolveDependency(typeof(DatabaseAvailabilityGuard))).thenReturn(availabilityGuard);
            when(dependencyResolver.ProvideDependency(typeof(TransactionIdStore))).thenReturn(txIdStore);

            GraphDatabaseAPI db = mock(typeof(GraphDatabaseAPI));

            when(Db.DependencyResolver).thenReturn(dependencyResolver);

            GraphDatabaseQueryService queryService = mock(typeof(GraphDatabaseQueryService));

            when(queryService.DependencyResolver).thenReturn(dependencyResolver);
            when(dependencyResolver.ResolveDependency(typeof(GraphDatabaseQueryService))).thenReturn(queryService);

            BoltChannel boltChannel = new BoltChannel("bolt-42", "bolt", new EmbeddedChannel());

            return(new TransactionStateMachineV1SPI(db, boltChannel, txAwaitDuration, clock));
        }
コード例 #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void startDb()
        public virtual void StartDb()
        {
            _graphDb = ( GraphDatabaseAPI )(new TestGraphDatabaseFactory()).newImpermanentDatabaseBuilder().setConfig(new Dictionary <string, string>()).newGraphDatabase();

            using (Transaction tx = _graphDb.beginTx())
            {
                // Create the node and relationship auto-indexes
                _graphDb.index().NodeAutoIndexer.Enabled = true;
                _graphDb.index().NodeAutoIndexer.startAutoIndexingProperty("nodeProp");
                _graphDb.index().RelationshipAutoIndexer.Enabled = true;
                _graphDb.index().RelationshipAutoIndexer.startAutoIndexingProperty("type");

                tx.Success();
            }

            using (Transaction tx = _graphDb.beginTx())
            {
                Node node1 = _graphDb.createNode();
                Node node2 = _graphDb.createNode();
                Node node3 = _graphDb.createNode();
                _id1 = node1.Id;
                _id2 = node2.Id;
                _id3 = node3.Id;
                Relationship rel = node1.CreateRelationshipTo(node2, RelationshipType.withName("FOO"));
                rel.SetProperty("type", "FOO");

                tx.Success();
            }
        }
コード例 #15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static java.util.List<org.neo4j.kernel.impl.transaction.TransactionRepresentation> createConstraintCreatingTransactions() throws Exception
        private static IList <TransactionRepresentation> CreateConstraintCreatingTransactions()
        {
            GraphDatabaseAPI db = ( GraphDatabaseAPI )(new TestGraphDatabaseFactory()).newImpermanentDatabase();

            try
            {
                using (Transaction tx = Db.beginTx())
                {
                    Db.schema().constraintFor(LABEL).assertPropertyIsUnique(KEY).create();
                    tx.Success();
                }

                LogicalTransactionStore           txStore = Db.DependencyResolver.resolveDependency(typeof(LogicalTransactionStore));
                IList <TransactionRepresentation> result  = new List <TransactionRepresentation>();
                using (TransactionCursor cursor = txStore.GetTransactions(Org.Neo4j.Kernel.impl.transaction.log.TransactionIdStore_Fields.BASE_TX_ID + 1))
                {
                    while (cursor.next())
                    {
                        result.Add(cursor.get().TransactionRepresentation);
                    }
                }
                return(result);
            }
            finally
            {
                Db.shutdown();
            }
        }
コード例 #16
0
        private void VerifyConstraints(GraphDatabaseAPI db, ConstraintType expectedConstraintType)
        {
            using (Transaction tx = Db.beginTx())
            {
                // only one index
                IEnumerator <ConstraintDefinition> constraints = Db.schema().Constraints.GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                assertTrue("has one index", constraints.hasNext());
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                ConstraintDefinition constraint = constraints.next();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                assertFalse("not more than one index", constraints.hasNext());

                Label          label          = constraint.Label;
                string         property       = constraint.PropertyKeys.GetEnumerator().next();
                ConstraintType constraintType = constraint.ConstraintType;

                // with correct pattern and provider
                assertEquals("correct label", "Person", label.Name());
                assertEquals("correct property", "name", property);
                assertEquals("correct constraint type", expectedConstraintType, constraintType);

                tx.Success();
            }
        }
コード例 #17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: public ExtensionService(@Context InputFormat input, @Context OutputFormat output, @Context PluginInvocator extensions, @Context Database database)
        public ExtensionService(InputFormat input, OutputFormat output, PluginInvocator extensions, Database database)
        {
            this._input      = input;
            this._output     = output;
            this._extensions = extensions;
            this._graphDb    = database.Graph;
        }
コード例 #18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @BeforeClass public static synchronized void startGraphDb()
        public static void StartGraphDb()
        {
            lock (typeof(ManagementBeansTest))
            {
                _graphDb = DbRule.GraphDatabaseAPI;
            }
        }
コード例 #19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static void checkInstance(Store store, org.neo4j.kernel.internal.GraphDatabaseAPI db) throws org.neo4j.internal.kernel.api.exceptions.KernelException
        private static void CheckInstance(Store store, GraphDatabaseAPI db)
        {
            CheckProvidedParameters(store, db);
            CheckGlobalNodeCount(store, db);
            CheckLabelCounts(db);
            CheckIndexCounts(store, db);
        }
コード例 #20
0
		 private void AssertDatabaseDoesNotHaveNodes( GraphDatabaseAPI database )
		 {
			  using ( Transaction ignored = database.BeginTx() )
			  {
					assertEquals( 0, database.AllNodes.Count() );
			  }
		 }
コード例 #21
0
 internal LocalStoreCopyRequester(GraphDatabaseAPI original, File originalDir, FileSystemAbstraction fs, bool includeLogs)
 {
     this.Original    = original;
     this.OriginalDir = originalDir;
     this.Fs          = fs;
     this.IncludeLogs = includeLogs;
 }
コード例 #22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void terminateLongRunningDriverQuery() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
		 public virtual void TerminateLongRunningDriverQuery()
		 {
			  GraphDatabaseAPI database = StartDatabaseWithTimeout();
			  KernelTransactionMonitor timeoutMonitor = database.DependencyResolver.resolveDependency( typeof( KernelTransactionMonitor ) );
			  OpenEnterpriseNeoServer neoServer = StartNeoServer( ( GraphDatabaseFacade ) database );

			  Org.Neo4j.driver.v1.Config driverConfig = DriverConfig;

			  using ( Driver driver = GraphDatabase.driver( "bolt://localhost:" + _boltPortDatabaseWithTimeout, driverConfig ), Session session = driver.session() )
			  {
					Org.Neo4j.driver.v1.Transaction transaction = session.beginTransaction();
					transaction.run( "create (n)" ).consume();
					transaction.success();
					_fakeClock.forward( 3, TimeUnit.SECONDS );
					timeoutMonitor.Run();
					try
					{
						 transaction.run( "create (n)" ).consume();
						 fail( "Transaction should be already terminated by execution guard." );
					}
					catch ( Exception )
					{
						 // ignored
					}
			  }
			  AssertDatabaseDoesNotHaveNodes( database );
		 }
コード例 #23
0
ファイル: GraphStoreFixture.cs プロジェクト: Neo4Net/Neo4Net
        private void GenerateInitialData()
        {
            GraphDatabaseBuilder builder = (new TestGraphDatabaseFactory()).newEmbeddedDatabaseBuilder(_directory.databaseDir());
            GraphDatabaseAPI     graphDb = ( GraphDatabaseAPI )builder.SetConfig(GraphDatabaseSettings.record_format, _formatName).setConfig(GraphDatabaseSettings.label_block_size, "60").setConfig("dbms.backup.enabled", "false").newGraphDatabase();

            try
            {
                GenerateInitialData(graphDb);
                StoreAccess stores = (new StoreAccess(graphDb.DependencyResolver.resolveDependency(typeof(RecordStorageEngine)).testAccessNeoStores())).initialize();
                _schemaId     = stores.SchemaStore.HighId;
                _nodeId       = stores.NodeStore.HighId;
                _labelId      = ( int )stores.LabelTokenStore.HighId;
                _nodeLabelsId = stores.NodeDynamicLabelStore.HighId;
                _relId        = stores.RelationshipStore.HighId;
                _relGroupId   = stores.RelationshipGroupStore.HighId;
                _propId       = ( int )stores.PropertyStore.HighId;
                _stringPropId = stores.StringStore.HighId;
                _arrayPropId  = stores.ArrayStore.HighId;
                _relTypeId    = ( int )stores.RelationshipTypeTokenStore.HighId;
                _propKeyId    = ( int )stores.PropertyKeyNameStore.HighId;
            }
            finally
            {
                graphDb.Shutdown();
            }
        }
コード例 #24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void terminateLongRunningQueryWithCustomTimeoutWithoutConfiguredDefault()
		 public virtual void TerminateLongRunningQueryWithCustomTimeoutWithoutConfiguredDefault()
		 {
			  GraphDatabaseAPI database = StartDatabaseWithoutTimeout();
			  KernelTransactionMonitor timeoutMonitor = database.DependencyResolver.resolveDependency( typeof( KernelTransactionMonitor ) );
			  using ( Transaction transaction = database.BeginTx( 5, TimeUnit.SECONDS ) )
			  {
					_fakeClock.forward( 4, TimeUnit.SECONDS );
					timeoutMonitor.Run();
					database.Execute( "create (n)" );
					transaction.Failure();
			  }

			  try
			  {
					  using ( Transaction transaction = database.BeginTx( 6, TimeUnit.SECONDS ) )
					  {
						_fakeClock.forward( 7, TimeUnit.SECONDS );
						timeoutMonitor.Run();
						transaction.Success();
						database.Execute( "create (n)" );
						fail( "Transaction should be already terminated." );
					  }
			  }
			  catch ( TransactionTerminatedException e )
			  {
					assertThat( e.Message, startsWith( "The transaction has been terminated." ) );
			  }

			  AssertDatabaseDoesNotHaveNodes( database );
		 }
コード例 #25
0
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: public java.util.Collection<org.neo4j.server.plugins.Injectable<?>> initializePackages(Iterable<String> packageNames)
        public virtual ICollection <Injectable <object> > InitializePackages(IEnumerable <string> packageNames)
        {
            GraphDatabaseAPI graphDatabaseService = _neoServer.Database.Graph;
            Config           configuration        = _neoServer.Config;

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Collection<org.neo4j.server.plugins.Injectable<?>> injectables = new java.util.HashSet<>();
            ICollection <Injectable <object> > injectables = new HashSet <Injectable <object> >();

            foreach (PluginLifecycle lifecycle in _lifecycles)
            {
                if (HasPackage(lifecycle, packageNames))
                {
                    if (lifecycle is SPIPluginLifecycle)
                    {
                        SPIPluginLifecycle lifeCycleSpi = ( SPIPluginLifecycle )lifecycle;
                        injectables.addAll(lifeCycleSpi.Start(_neoServer));
                    }
                    else
                    {
                        injectables.addAll(lifecycle.Start(graphDatabaseService, new ConfigAdapter(configuration)));
                    }
                }
            }
            return(injectables);
        }
コード例 #26
0
        private static void CheckLabelCounts(GraphDatabaseAPI db)
        {
            using (Transaction ignored = Db.beginTx())
            {
                Dictionary <Label, long> counts = new Dictionary <Label, long>();
                foreach (Node node in Db.AllNodes)
                {
                    foreach (Label label in node.Labels)
                    {
                        long?count = counts[label];
                        if (count != null)
                        {
                            counts[label] = count + 1;
                        }
                        else
                        {
                            counts[label] = 1L;
                        }
                    }
                }

                ThreadToStatementContextBridge bridge = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));
                KernelTransaction kernelTransaction   = bridge.GetKernelTransactionBoundToThisThread(true);

                foreach (KeyValuePair <Label, long> entry in Counts.SetOfKeyValuePairs())
                {
                    assertEquals(entry.Value.longValue(), kernelTransaction.DataRead().countsForNode(kernelTransaction.TokenRead().nodeLabel(entry.Key.name())));
                }
            }
        }
コード例 #27
0
ファイル: CountsRotationTest.cs プロジェクト: Neo4Net/Neo4Net
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRotateCountsStoreWhenRotatingLog() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRotateCountsStoreWhenRotatingLog()
        {
            // GIVEN
            GraphDatabaseAPI db = ( GraphDatabaseAPI )_dbBuilder.newGraphDatabase();

            // WHEN doing a transaction (actually two, the label-mini-tx also counts)
            using (Transaction tx = Db.beginTx())
            {
                Db.createNode(_b);
                tx.Success();
            }
            // and rotating the log (which implies flushing)
            CheckPoint(db);
            // and creating another node after it
            using (Transaction tx = Db.beginTx())
            {
                Db.createNode(_c);
                tx.Success();
            }

            // THEN
            assertTrue(_fs.fileExists(AlphaStoreFile()));
            assertTrue(_fs.fileExists(BetaStoreFile()));

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.io.pagecache.PageCache pageCache = db.getDependencyResolver().resolveDependency(org.neo4j.io.pagecache.PageCache.class);
            PageCache pageCache = Db.DependencyResolver.resolveDependency(typeof(PageCache));

            using (Lifespan life = new Lifespan())
            {
                CountsTracker store = life.Add(CreateCountsTracker(pageCache));
                // NOTE since the rotation happens before the second transaction is committed we do not see those changes
                // in the stats
                // a transaction for creating the label and a transaction for the node
                assertEquals(BASE_TX_ID + 1 + 1, store.TxId());
                assertEquals(INITIAL_MINOR_VERSION, store.MinorVersion());
                // one for all nodes and one for the created "B" label
                assertEquals(1 + 1, store.TotalEntriesStored());
                assertEquals(1 + 1, AllRecords(store).Count);
            }

            // on the other hand the tracker should read the correct value by merging data on disk and data in memory
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final CountsTracker tracker = db.getDependencyResolver().resolveDependency(org.neo4j.kernel.impl.storageengine.impl.recordstorage.RecordStorageEngine.class).testAccessNeoStores().getCounts();
            CountsTracker tracker = Db.DependencyResolver.resolveDependency(typeof(RecordStorageEngine)).testAccessNeoStores().Counts;

            assertEquals(1 + 1, tracker.NodeCount(-1, newDoubleLongRegister()).readSecond());

            int labelId;

            using (Transaction tx = Db.beginTx())
            {
                KernelTransaction transaction = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge)).getKernelTransactionBoundToThisThread(true);
                labelId = transaction.TokenRead().nodeLabel(_c.name());
            }
            assertEquals(1, tracker.NodeCount(labelId, newDoubleLongRegister()).readSecond());

            Db.shutdown();
        }
コード例 #28
0
 private void CreateNode(GraphDatabaseAPI db, string name)
 {
     using (Transaction tx = Db.beginTx())
     {
         Db.createNode(LABEL).setProperty(KEY, name);
         tx.Success();
     }
 }
コード例 #29
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @After public void stopDb()
        public virtual void StopDb()
        {
            if (_graphDb != null)
            {
                _graphDb.shutdown();
            }
            _graphDb = null;
        }
コード例 #30
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private String contentOf(String file) throws java.io.IOException
        private string ContentOf(string file)
        {
            GraphDatabaseAPI api           = ( GraphDatabaseAPI )Neo4j.GraphDatabaseService;
            Config           config        = api.DependencyResolver.resolveDependency(typeof(Config));
            File             dataDirectory = config.Get(GraphDatabaseSettings.data_directory);

            return(new string( Files.readAllBytes((new File(dataDirectory, file)).toPath()), UTF_8 ));
        }