Esempio n. 1
0
        private void BaseTestForElectionOk(ISet <InstanceId> failed, bool moreThanQuorum)
        {
            IDictionary <InstanceId, URI> members = new Dictionary <InstanceId, URI>();

            members[new InstanceId(1)] = URI.create("server1");
            members[new InstanceId(2)] = URI.create("server2");
            members[new InstanceId(3)] = URI.create("server3");

            Config config = mock(typeof(Config));

            when(config.Get(ClusterSettings.max_acceptors)).thenReturn(10);

            ClusterConfiguration clusterConfiguration = mock(typeof(ClusterConfiguration));

            when(clusterConfiguration.Members).thenReturn(members);

            ClusterContext clusterContext = mock(typeof(ClusterContext));

            when(clusterContext.Configuration).thenReturn(clusterConfiguration);

            MultiPaxosContext context = new MultiPaxosContext(new InstanceId(1), Iterables.iterable(new ElectionRole("coordinator")), clusterConfiguration, mock(typeof(Executor)), NullLogProvider.Instance, mock(typeof(ObjectInputStreamFactory)), mock(typeof(ObjectOutputStreamFactory)), mock(typeof(AcceptorInstanceStore)), mock(typeof(Timeouts)), mock(typeof(ElectionCredentialsProvider)), config);

            context.HeartbeatContext.Failed.addAll(failed);

            ElectionContext toTest = context.ElectionContext;

            assertEquals(moreThanQuorum, !toTest.ElectionOk());
        }
Esempio n. 2
0
        public static void EncodeValue(PropertyBlock block, int keyId, Value value, DynamicRecordAllocator stringAllocator, DynamicRecordAllocator arrayAllocator, bool allowStorePointsAndTemporal)
        {
            if (value is ArrayValue)
            {
                object asObject = value.AsObject();

                // Try short array first, i.e. inlined in the property block
                if (ShortArray.encode(keyId, asObject, block, PropertyType.PayloadSize))
                {
                    return;
                }

                // Fall back to dynamic array store
                IList <DynamicRecord> arrayRecords = new List <DynamicRecord>();
                AllocateArrayRecords(arrayRecords, asObject, arrayAllocator, allowStorePointsAndTemporal);
                SetSingleBlockValue(block, keyId, PropertyType.Array, Iterables.first(arrayRecords).Id);
                foreach (DynamicRecord valueRecord in arrayRecords)
                {
                    valueRecord.SetType(PropertyType.Array.intValue());
                }
                block.ValueRecords = arrayRecords;
            }
            else
            {
                value.WriteTo(new PropertyBlockValueWriter(block, keyId, stringAllocator, allowStorePointsAndTemporal));
            }
        }
Esempio n. 3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void deleteAllNodesAndTheirLabels()
        public virtual void DeleteAllNodesAndTheirLabels()
        {
            // GIVEN
            GraphDatabaseService db = DbRule.GraphDatabaseAPI;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Label label = label("A");
            Label label = label("A");

            using (Transaction tx = Db.beginTx())
            {
                Node node = Db.createNode();
                node.AddLabel(label);
                node.SetProperty("name", "bla");
                tx.Success();
            }

            // WHEN
            using (Transaction tx = Db.beginTx())
            {
                foreach (Node node in Db.AllNodes)
                {
                    node.removeLabel(label);                    // remove Label ...
                    node.delete();                              // ... and afterwards the node
                }
                tx.Success();
            }               // tx.close(); - here comes the exception

            // THEN
            using (Transaction ignored = Db.beginTx())
            {
                assertEquals(0, Iterables.count(Db.AllNodes));
            }
        }
Esempio n. 4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testClose()
        public virtual void TestClose()
        {
            DynamicArrayStore           store   = CreateDynamicArrayStore();
            ICollection <DynamicRecord> records = new List <DynamicRecord>();

            store.AllocateRecordsFromBytes(records, new sbyte[10]);
            long blockId = Iterables.first(records).Id;

            foreach (DynamicRecord record in records)
            {
                store.UpdateRecord(record);
            }
            _neoStores.close();
            _neoStores = null;
            try
            {
                store.GetArrayFor(store.GetRecords(blockId, NORMAL));
                fail("Closed store should throw exception");
            }
            catch (Exception)
            {               // good
            }
            try
            {
                store.GetRecords(0, NORMAL);
                fail("Closed store should throw exception");
            }
            catch (Exception)
            {               // good
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Test creates a situation where streaming of a node fails when accessing node labels/properties.
        /// It fails because transaction is terminated. Bolt server should not send half-written message.
        /// Driver should receive a regular FAILURE message saying that transaction has been terminated.
        /// </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldTransmitStreamingFailure()
        public virtual void ShouldTransmitStreamingFailure()
        {
            using (Session session = _driver.session())
            {
                IDictionary <string, object> @params = new Dictionary <string, object>();
                @params["name1"] = RandomLongString();
                @params["name2"] = RandomLongString();
                session.run("CREATE (n1 :Person {name: $name1}), (n2 :Person {name: $name2}) RETURN n1, n2", @params).consume();

                StatementResult result = session.run("CALL test.readNodesReturnThemAndTerminateTheTransaction() YIELD node");

                assertTrue(result.hasNext());
                Record record = result.next();
                assertEquals("Person", Iterables.single(record.get(0).asNode().labels()));
                assertNotNull(record.get(0).asNode().get("name"));

                try
                {
                    result.hasNext();
                    fail("Exception expected");
                }
                catch (TransientException e)
                {
                    assertEquals(Org.Neo4j.Kernel.Api.Exceptions.Status_Transaction.Terminated.code().serialize(), e.code());
                }
            }
        }
Esempio n. 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void processAllRelationshipProperties() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ProcessAllRelationshipProperties()
        {
            CreateAlistairAndStefanNodes();
            CopyUpdateVisitor     propertyUpdateVisitor = new CopyUpdateVisitor();
            RelationshipStoreScan relationshipStoreScan = new RelationshipStoreScan(new RecordStorageReader(_neoStores), _locks, propertyUpdateVisitor, new int[] { _relTypeId }, id => true);

            using (StorageRelationshipScanCursor relationshipScanCursor = _reader.allocateRelationshipScanCursor())
            {
                relationshipScanCursor.Single(1);
                relationshipScanCursor.Next();

                relationshipStoreScan.process(relationshipScanCursor);
            }

            EntityUpdates propertyUpdates = propertyUpdateVisitor.PropertyUpdates;

            assertNotNull("Visitor should contain container with updates.", propertyUpdates);

            RelationTypeSchemaDescriptor         index1  = SchemaDescriptorFactory.forRelType(0, 2);
            RelationTypeSchemaDescriptor         index2  = SchemaDescriptorFactory.forRelType(0, 3);
            RelationTypeSchemaDescriptor         index3  = SchemaDescriptorFactory.forRelType(0, 2, 3);
            RelationTypeSchemaDescriptor         index4  = SchemaDescriptorFactory.forRelType(1, 3);
            IList <RelationTypeSchemaDescriptor> indexes = Arrays.asList(index1, index2, index3, index4);

//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            assertThat(Iterables.map(IndexEntryUpdate::indexKey, propertyUpdates.ForIndexKeys(indexes)), containsInAnyOrder(index1, index2, index3));
        }
Esempio n. 7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void createIndexWithProviderThatUsesNeoAsDataSource()
        internal virtual void CreateIndexWithProviderThatUsesNeoAsDataSource()
        {
            string indexName = "inneo";

            assertFalse(IndexExists(indexName));
            IDictionary <string, string> config = stringMap(PROVIDER, "test-dummy-neo-index", "config1", "A value", "another config", "Another value");

            Index <Node> index;

            using (Transaction transaction = _db.beginTx())
            {
                index = _db.index().forNodes(indexName, config);
                transaction.Success();
            }

            using (Transaction tx = _db.beginTx())
            {
                assertTrue(IndexExists(indexName));
                assertEquals(config, _db.index().getConfiguration(index));
                using (IndexHits <Node> indexHits = index.get("key", "something else"))
                {
                    assertEquals(0, Iterables.count(indexHits));
                }
                tx.Success();
            }

            RestartDb();

            using (Transaction tx = _db.beginTx())
            {
                assertTrue(IndexExists(indexName));
                assertEquals(config, _db.index().getConfiguration(index));
                tx.Success();
            }
        }
Esempio n. 8
0
 private long CountNodes()
 {
     using (Transaction transaction = Graphdb().beginTx())
     {
         return(Iterables.count(Graphdb().AllNodes));
     }
 }
Esempio n. 9
0
 private IList <ConstraintDefinition> Constraints(GraphDatabaseService database)
 {
     using (Transaction ignored = database.BeginTx())
     {
         return(Iterables.asList(database.Schema().Constraints));
     }
 }
Esempio n. 10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCreateRelationship() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldCreateRelationship()
        {
            long n1, n2;

            using (Org.Neo4j.Graphdb.Transaction tx = graphDb.beginTx())
            {
                n1 = graphDb.createNode().Id;
                n2 = graphDb.createNode().Id;
                tx.Success();
            }

            long r;

            using (Transaction tx = beginTransaction())
            {
                int label = tx.token().relationshipTypeGetOrCreateForName("R");
                r = tx.dataWrite().relationshipCreate(n1, label, n2);
                tx.Success();
            }

            using (Org.Neo4j.Graphdb.Transaction ignore = graphDb.beginTx())
            {
                IList <Relationship> relationships = Iterables.asList(graphDb.getNodeById(n1).Relationships);
                assertEquals(1, relationships.Count);
                assertEquals(relationships[0].Id, r);
            }
        }
Esempio n. 11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void lazyLoadWithinWriteTransaction() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void LazyLoadWithinWriteTransaction()
        {
            // Given
            FileSystemAbstraction fileSystem = Fs.get();
            BatchInserter         inserter   = BatchInserters.inserter(TestDirectory.databaseDir(), fileSystem);
            int  count  = 3000;
            long nodeId = inserter.CreateNode(MapWithManyProperties(count));

            inserter.Shutdown();

            GraphDatabaseService db = (new TestGraphDatabaseFactory()).setFileSystem(fileSystem).newImpermanentDatabase(TestDirectory.databaseDir());

            // When
            try
            {
                using (Transaction tx = Db.beginTx())
                {
                    Db.createNode();
                    Node node = Db.getNodeById(nodeId);

                    // Then
                    assertEquals(count, Iterables.count(node.PropertyKeys));
                    tx.Success();
                }
            }
            finally
            {
                Db.shutdown();
            }
        }
Esempio n. 12
0
            public virtual ICollection <Path> DoContainerLogAggregation(AggregatedLogFormat.LogWriter
                                                                        writer, bool appFinished)
            {
                AppLogAggregatorImpl.Log.Info("Uploading logs for container " + this.containerId
                                              + ". Current good log dirs are " + StringUtils.Join(",", this._enclosing.dirsHandler
                                                                                                  .GetLogDirsForRead()));
                AggregatedLogFormat.LogKey logKey = new AggregatedLogFormat.LogKey(this.containerId
                                                                                   );
                AggregatedLogFormat.LogValue logValue = new AggregatedLogFormat.LogValue(this._enclosing
                                                                                         .dirsHandler.GetLogDirsForRead(), this.containerId, this._enclosing.userUgi.GetShortUserName
                                                                                             (), this._enclosing.logAggregationContext, this.uploadedFileMeta, appFinished);
                try
                {
                    writer.Append(logKey, logValue);
                }
                catch (Exception e)
                {
                    AppLogAggregatorImpl.Log.Error("Couldn't upload logs for " + this.containerId + ". Skipping this container."
                                                   , e);
                    return(new HashSet <Path>());
                }
                Sharpen.Collections.AddAll(this.uploadedFileMeta, logValue.GetCurrentUpLoadedFileMeta
                                               ());
                // if any of the previous uploaded logs have been deleted,
                // we need to remove them from alreadyUploadedLogs
                IEnumerable <string> mask = Iterables.Filter(this.uploadedFileMeta, new _Predicate_581
                                                                 (logValue));

                this.uploadedFileMeta = Sets.NewHashSet(mask);
                return(logValue.GetCurrentUpLoadedFilesPath());
            }
        public override EvaluationResult evaluate <T1>(IEnumerable <T1> iterable, CalculationFunctions functions, string firstToken, IList <string> remainingTokens)
        {
            string token = firstToken.ToLower(Locale.ENGLISH);
            int?   index = Ints.tryParse(token);

            if (index != null)
            {
                try
                {
                    return(EvaluationResult.success(Iterables.get(iterable, index), remainingTokens));
                }
                catch (System.IndexOutOfRangeException)
                {
                    return(invalidTokenFailure(iterable, token));
                }
            }
            ISet <string> tokens = this.tokens(iterable);

            foreach (object item in iterable)
            {
                if (!fieldValues(item).Contains(token))
                {
                    continue;
                }
                if (!tokens.Contains(token))
                {
                    return(ambiguousTokenFailure(iterable, token));
                }
                return(EvaluationResult.success(item, remainingTokens));
            }
            return(invalidTokenFailure(iterable, token));
        }
Esempio n. 14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testElectionNotOkQuorumFailedTwoInstances()
        public virtual void TestElectionNotOkQuorumFailedTwoInstances()
        {
            ISet <InstanceId> failed = new HashSet <InstanceId>();

            failed.Add(new InstanceId(2));

            IDictionary <InstanceId, URI> members = new Dictionary <InstanceId, URI>();

            members[new InstanceId(1)] = URI.create("server1");
            members[new InstanceId(2)] = URI.create("server2");

            Config config = mock(typeof(Config));

            when(config.Get(ClusterSettings.max_acceptors)).thenReturn(10);

            ClusterConfiguration clusterConfiguration = mock(typeof(ClusterConfiguration));

            when(clusterConfiguration.Members).thenReturn(members);

            ClusterContext clusterContext = mock(typeof(ClusterContext));

            when(clusterContext.Configuration).thenReturn(clusterConfiguration);

            MultiPaxosContext context = new MultiPaxosContext(new InstanceId(1), Iterables.iterable(new ElectionRole("coordinator")), clusterConfiguration, mock(typeof(Executor)), NullLogProvider.Instance, mock(typeof(ObjectInputStreamFactory)), mock(typeof(ObjectOutputStreamFactory)), mock(typeof(AcceptorInstanceStore)), mock(typeof(Timeouts)), mock(typeof(ElectionCredentialsProvider)), config);

            context.HeartbeatContext.Failed.addAll(failed);

            ElectionContext toTest = context.ElectionContext;

            assertFalse(toTest.ElectionOk());
        }
Esempio n. 15
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void sortFriendsByName()
        public virtual void SortFriendsByName()
        {
            /*
             *      (Abraham)
             *          |
             *         (me)--(George)--(Dan)
             *          |        |
             *       (Zack)---(Andreas)
             *                   |
             *              (Nicholas)
             */

            string me       = "me";
            string abraham  = "Abraham";
            string george   = "George";
            string dan      = "Dan";
            string zack     = "Zack";
            string andreas  = "Andreas";
            string nicholas = "Nicholas";
            string knows    = "KNOWS";

            CreateGraph(Triplet(me, knows, abraham), Triplet(me, knows, george), Triplet(george, knows, dan), Triplet(me, knows, zack), Triplet(zack, knows, andreas), Triplet(george, knows, andreas), Triplet(andreas, knows, nicholas));

            using (Transaction tx = BeginTx())
            {
                IList <Node> nodes = AsNodes(abraham, george, dan, zack, andreas, nicholas);
                assertEquals(nodes, Iterables.asCollection(GraphDb.traversalDescription().evaluator(excludeStartPosition()).sort(endNodeProperty("name")).traverse(GetNodeWithName(me)).nodes()));
                tx.Success();
            }
        }
Esempio n. 16
0
 private IList <IndexDefinition> Indexes(GraphDatabaseService database)
 {
     using (Transaction ignored = database.BeginTx())
     {
         return(Iterables.asList(database.Schema().Indexes));
     }
 }
Esempio n. 17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void processAllNodeProperties() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ProcessAllNodeProperties()
        {
            CopyUpdateVisitor      propertyUpdateVisitor  = new CopyUpdateVisitor();
            StoreViewNodeStoreScan storeViewNodeStoreScan = new StoreViewNodeStoreScan(new RecordStorageReader(_neoStores), _locks, null, propertyUpdateVisitor, new int[] { _labelId }, id => true);

            using (StorageNodeCursor nodeCursor = _reader.allocateNodeCursor())
            {
                nodeCursor.Single(1);
                nodeCursor.Next();

                storeViewNodeStoreScan.process(nodeCursor);
            }

            EntityUpdates propertyUpdates = propertyUpdateVisitor.PropertyUpdates;

            assertNotNull("Visitor should contain container with updates.", propertyUpdates);

            LabelSchemaDescriptor         index1  = SchemaDescriptorFactory.forLabel(0, 0);
            LabelSchemaDescriptor         index2  = SchemaDescriptorFactory.forLabel(0, 1);
            LabelSchemaDescriptor         index3  = SchemaDescriptorFactory.forLabel(0, 0, 1);
            LabelSchemaDescriptor         index4  = SchemaDescriptorFactory.forLabel(1, 1);
            IList <LabelSchemaDescriptor> indexes = Arrays.asList(index1, index2, index3, index4);

//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            assertThat(Iterables.map(IndexEntryUpdate::indexKey, propertyUpdates.ForIndexKeys(indexes)), containsInAnyOrder(index1, index2, index3));
        }
Esempio n. 18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void getAllRelationships()
        public virtual void getAllRelationships()
        {
            ISet <Relationship> existingRelationships = Iterables.addToCollection(GraphDb.AllRelationships, new HashSet <Relationship>());

            ISet <Relationship> createdRelationships = new HashSet <Relationship>();
            Node node = GraphDb.createNode();

            for (int i = 0; i < 100; i++)
            {
                createdRelationships.Add(node.CreateRelationshipTo(GraphDb.createNode(), TEST));
            }
            NewTransaction();

            ISet <Relationship> allRelationships = new HashSet <Relationship>();

            allRelationships.addAll(existingRelationships);
            allRelationships.addAll(createdRelationships);

            int count = 0;

            foreach (Relationship rel in GraphDb.AllRelationships)
            {
                assertTrue("Unexpected rel " + rel + ", expected one of " + allRelationships, allRelationships.Contains(rel));
                count++;
            }
            assertEquals(allRelationships.Count, count);
        }
Esempio n. 19
0
 /// <exception cref="System.IO.IOException"/>
 public static void SaveSegmentFiles([NotNull] string jpegFilePath, [NotNull] JpegSegmentData segmentData)
 {
     foreach (JpegSegmentType segmentType in segmentData.GetSegmentTypes())
     {
         IList <sbyte[]> segments = Iterables.ToList(segmentData.GetSegments(segmentType));
         if (segments.Count == 0)
         {
             continue;
         }
         if (segments.Count > 1)
         {
             for (int i = 0; i < segments.Count; i++)
             {
                 string outputFilePath = Sharpen.Extensions.StringFormat("%s.%s.%d", jpegFilePath, Sharpen.Extensions.ConvertToString(segmentType).ToLower(), i);
                 System.Console.Out.Println("Writing: " + outputFilePath);
                 FileUtil.SaveBytes(new FilePath(outputFilePath), segments[i]);
             }
         }
         else
         {
             string outputFilePath = Sharpen.Extensions.StringFormat("%s.%s", jpegFilePath, Sharpen.Extensions.ConvertToString(segmentType).ToLower());
             System.Console.Out.Println("Writing: " + outputFilePath);
             FileUtil.SaveBytes(new FilePath(outputFilePath), segments[0]);
         }
     }
 }
Esempio n. 20
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createAndClearCacheBeforeCommit()
        public virtual void CreateAndClearCacheBeforeCommit()
        {
            Node node = GraphDb.createNode();

            node.CreateRelationshipTo(GraphDb.createNode(), TEST);
            assertEquals(1, Iterables.count(node.Relationships));
        }
Esempio n. 21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldClearSlavesWhenNewMasterElected()
        public virtual void ShouldClearSlavesWhenNewMasterElected()
        {
            // given
            Cluster        cluster        = mock(typeof(Cluster));
            ClusterMembers clusterMembers = mock(typeof(ClusterMembers));

            when(clusterMembers.AliveMembers).thenReturn(Iterables.option((new ClusterMember(_instanceId)).availableAs(SLAVE, _haUri, StoreId.DEFAULT)));

            SlaveFactory slaveFactory = mock(typeof(SlaveFactory));
            Slave        slave1       = mock(typeof(Slave));
            Slave        slave2       = mock(typeof(Slave));

            when(slaveFactory.NewSlave(any(typeof(LifeSupport)), any(typeof(ClusterMember)), any(typeof(string)), any(typeof(Integer)))).thenReturn(slave1, slave2);

            HighAvailabilitySlaves slaves = new HighAvailabilitySlaves(clusterMembers, cluster, slaveFactory, new HostnamePort("localhost", 0));

            slaves.Init();

            ArgumentCaptor <ClusterListener> listener = ArgumentCaptor.forClass(typeof(ClusterListener));

            verify(cluster).addClusterListener(listener.capture());

            // when
            Slave actualSlave1 = slaves.Slaves.GetEnumerator().next();

            listener.Value.elected(ClusterConfiguration.COORDINATOR, _instanceId, _clusterUri);

            Slave actualSlave2 = slaves.Slaves.GetEnumerator().next();

            // then
            assertThat(actualSlave2, not(sameInstance(actualSlave1)));
        }
Esempio n. 22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldLoadAllRelationships()
        public virtual void ShouldLoadAllRelationships()
        {
            // GIVEN
            GraphDatabaseService db = GraphDbAPI;
            Node node;

            using (Transaction tx = Db.beginTx())
            {
                node = Db.createNode();
                for (int i = 0; i < 112; i++)
                {
                    node.CreateRelationshipTo(Db.createNode(), TEST);
                    Db.createNode().createRelationshipTo(node, TEST);
                }
                tx.Success();
            }
            // WHEN
            long one;
            long two;

            using (Transaction tx = Db.beginTx())
            {
                one = Iterables.count(node.GetRelationships(TEST, Direction.OUTGOING));
                two = Iterables.count(node.GetRelationships(TEST, Direction.OUTGOING));
                tx.Success();
            }

            // THEN
            assertEquals(two, one);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldPopulateAndUpdate() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldPopulateAndUpdate()
        {
            // GIVEN
            WithPopulator(IndexProvider.getPopulator(Descriptor, IndexSamplingConfig, heapBufferFactory(1024)), p => p.add(Updates(ValueSet1)));

            using (IndexAccessor accessor = IndexProvider.getOnlineAccessor(Descriptor, IndexSamplingConfig))
            {
                // WHEN
                using (IndexUpdater updater = accessor.NewUpdater(IndexUpdateMode.ONLINE))
                {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<IndexEntryUpdate<?>> updates = updates(valueSet2);
                    IList <IndexEntryUpdate <object> > updates = updates(ValueSet2);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (IndexEntryUpdate<?> update : updates)
                    foreach (IndexEntryUpdate <object> update in updates)
                    {
                        updater.Process(update);
                    }
                }

                // THEN
                using (IndexReader reader = new QueryResultComparingIndexReader(accessor.NewReader()))
                {
                    int propertyKeyId = Descriptor.schema().PropertyId;
                    foreach (NodeAndValue entry in Iterables.concat(ValueSet1, ValueSet2))
                    {
                        NodeValueIterator nodes = new NodeValueIterator();
                        reader.Query(nodes, IndexOrder.NONE, false, IndexQuery.exact(propertyKeyId, entry.Value));
                        assertEquals(entry.NodeId, nodes.Next());
                        assertFalse(nodes.HasNext());
                    }
                }
            }
        }
Esempio n. 24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void convertNodeToDense()
        public virtual void ConvertNodeToDense()
        {
            Node node = GraphDb.createNode();
            Dictionary <MyRelTypes, ISet <Relationship> > rels = new Dictionary <MyRelTypes, ISet <Relationship> >(typeof(MyRelTypes));

            foreach (MyRelTypes type in Enum.GetValues(typeof(MyRelTypes)))
            {
                rels[type] = new HashSet <Relationship>();
            }
            int expectedRelCount = 0;

            for (int i = 0; i < 6; i++, expectedRelCount++)
            {
                MyRelTypes   type = Enum.GetValues(typeof(MyRelTypes))[i % Enum.GetValues(typeof(MyRelTypes)).length];
                Relationship rel  = node.CreateRelationshipTo(GraphDb.createNode(), type);
                rels[type].Add(rel);
            }
            NewTransaction();
            for (int i = 0; i < 1000; i++, expectedRelCount++)
            {
                node.CreateRelationshipTo(GraphDb.createNode(), MyRelTypes.TEST);
            }

            assertEquals(expectedRelCount, node.Degree);
            assertEquals(expectedRelCount, node.GetDegree(Direction.BOTH));
            assertEquals(expectedRelCount, node.GetDegree(Direction.OUTGOING));
            assertEquals(0, node.GetDegree(Direction.INCOMING));
            assertEquals(rels[MyRelTypes.TEST2], Iterables.asSet(node.GetRelationships(MyRelTypes.TEST2)));
            assertEquals(Join(rels[MyRelTypes.TEST_TRAVERSAL], rels[MyRelTypes.TEST2]), Iterables.asSet(node.GetRelationships(MyRelTypes.TEST_TRAVERSAL, MyRelTypes.TEST2)));
        }
Esempio n. 25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotLeaveAnyStateBehindAfterFailingToCreateConstraint()
        public virtual void ShouldNotLeaveAnyStateBehindAfterFailingToCreateConstraint()
        {
            // given
            using (Org.Neo4j.Graphdb.Transaction tx = Db.beginTx())
            {
                CreateOffendingDataInRunningTx(db);
                tx.Success();
            }

            // when
            try
            {
                using (Org.Neo4j.Graphdb.Transaction tx = Db.beginTx())
                {
                    CreateConstraintInRunningTx(db, KEY, PROP);

                    tx.Success();
                    fail("expected failure");
                }
            }
            catch (QueryExecutionException e)
            {
                assertThat(e.Message, startsWith("Unable to create CONSTRAINT"));
            }

            // then
            using (Org.Neo4j.Graphdb.Transaction tx = Db.beginTx())
            {
                assertEquals(System.Linq.Enumerable.Empty <ConstraintDefinition>(), Iterables.asList(Db.schema().Constraints));
                assertEquals(System.Linq.Enumerable.Empty <IndexDefinition, Org.Neo4j.Graphdb.schema.Schema_IndexState>(), IndexesWithState(Db.schema()));
                tx.Success();
            }
        }
Esempio n. 26
0
 private long CountIndexes()
 {
     using (Transaction transaction = _database.beginTx())
     {
         return(Iterables.count(_database.schema().Indexes));
     }
 }
Esempio n. 27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void whenContextClassLoaderDuplicatesServiceShouldLoadItOnce()
        internal virtual void WhenContextClassLoaderDuplicatesServiceShouldLoadItOnce()
        {
            Thread.CurrentThread.ContextClassLoader = typeof(Service).ClassLoader;
            IEnumerable <FooService> services = Service.Load(typeof(FooService));

            assertEquals(1, Iterables.count(services));
        }
Esempio n. 28
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void something() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void Something()
        {
            object acceptorValue = new object();
            object bookedValue   = new object();

            Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId instanceId = new Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId(42);

            PaxosInstanceStore paxosInstanceStore = new PaxosInstanceStore();

            ProposerContext context = Mockito.mock(typeof(ProposerContext));

            when(context.GetPaxosInstance(instanceId)).thenReturn(paxosInstanceStore.GetPaxosInstance(instanceId));
            when(context.GetMinimumQuorumSize(Mockito.anyList())).thenReturn(2);

            // The instance is closed
            PaxosInstance paxosInstance = new PaxosInstance(paxosInstanceStore, instanceId);                 // the instance

            paxosInstance.Propose(2001, Iterables.asList(Iterables.iterable(create("http://something1"), create("http://something2"), create("http://something3"))));

            Message message = Message.to(ProposerMessage.Promise, create("http://something1"), new ProposerMessage.PromiseState(2001, acceptorValue));

            message.setHeader(Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId.INSTANCE, instanceId.ToString());

            MessageHolder mockHolder = mock(typeof(MessageHolder));

            ProposerState.Proposer.handle(context, message, mockHolder);
        }
Esempio n. 29
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldDumpProcessInformation() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldDumpProcessInformation()
        {
            // GIVEN
            File directory = TestDirectory.directory("dump");
            // a process spawned from this test which pauses at a specific point of execution
            string java = JavaExecutable.ToString();
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
            Process process = Runtime.exec(new string[] { java,"-cp",ClassPath,typeof(DumpableProcess).FullName,SIGNAL });

            AwaitSignal(process);

            // WHEN
            // dumping process information for that spawned process (knowing it's in the expected position)
            DumpProcessInformation            dumper = new DumpProcessInformation(NullLogProvider.Instance,directory);
            ICollection <Pair <long,string> > pids   = dumper.GetJPids(containsString(typeof(DumpableProcess).Name));

            // bail if our Java installation is wonky and `jps` doesn't work
            assumeThat(pids.Count,greaterThan(0));

            Pair <long,string> pid = Iterables.single(pids);
            File threaddumpFile    = dumper.DoThreadDump(pid);

            process.destroy();

            // THEN
            // the produced thread dump should contain that expected method at least
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
            assertTrue(FileContains(threaddumpFile,"traceableMethod",typeof(DumpableProcess).FullName));
        }
Esempio n. 30
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAllowForcedCopyOverAnExistingDatabase() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAllowForcedCopyOverAnExistingDatabase()
        {
            // given
            string databaseName = "to";
            Config config       = ConfigWith(databaseName, Directory.absolutePath().AbsolutePath);

            File fromPath      = new File(Directory.absolutePath(), "from");
            File toPath        = config.Get(GraphDatabaseSettings.database_path);
            int  fromNodeCount = 10;
            int  toNodeCount   = 20;

            CreateDbAt(fromPath, fromNodeCount);
            CreateDbAt(toPath, toNodeCount);

            // when
            (new RestoreDatabaseCommand(FileSystemRule.get(), fromPath, config, databaseName, true)).execute();

            // then
            GraphDatabaseService copiedDb = (new GraphDatabaseFactory()).newEmbeddedDatabaseBuilder(toPath).setConfig(OnlineBackupSettings.online_backup_enabled, Settings.FALSE).newGraphDatabase();

            using (Transaction ignored = copiedDb.BeginTx())
            {
                assertEquals(fromNodeCount, Iterables.count(copiedDb.AllNodes));
            }

            copiedDb.Shutdown();
        }