Exemplo n.º 1
0
        private void ShowRelCounts(KernelTransaction ktx, DbStructureVisitor visitor)
        {
            // all wildcards
            NoSide(ktx, visitor, _wildcardRelType, ANY_RELATIONSHIP_TYPE);

            TokenRead tokenRead = ktx.TokenRead();

            // one label only
            foreach (Label label in _db.AllLabels)
            {
                int labelId = tokenRead.NodeLabel(label.Name());

                LeftSide(ktx, visitor, label, labelId, _wildcardRelType, ANY_RELATIONSHIP_TYPE);
                RightSide(ktx, visitor, label, labelId, _wildcardRelType, ANY_RELATIONSHIP_TYPE);
            }

            // fixed rel type
            foreach (RelationshipType relType in _db.AllRelationshipTypes)
            {
                int relTypeId = tokenRead.RelationshipType(relType.Name());
                NoSide(ktx, visitor, relType, relTypeId);

                foreach (Label label in _db.AllLabels)
                {
                    int labelId = tokenRead.NodeLabel(label.Name());

                    // wildcard on right
                    LeftSide(ktx, visitor, label, labelId, relType, relTypeId);

                    // wildcard on left
                    RightSide(ktx, visitor, label, labelId, relType, relTypeId);
                }
            }
        }
Exemplo n.º 2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void batchInserterShouldUseConfiguredIndexProvider() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void BatchInserterShouldUseConfiguredIndexProvider()
        {
            Config        config   = Config.defaults(stringMap(default_schema_provider.name(), _schemaIndex.providerName()));
            BatchInserter inserter = NewBatchInserter(config);

            inserter.CreateDeferredSchemaIndex(TestLabels.LABEL_ONE).on("key").create();
            inserter.Shutdown();
            GraphDatabaseService db = GraphDatabaseService(config);

            AwaitIndexesOnline(db);
            try
            {
                using (Transaction tx = Db.beginTx())
                {
                    DependencyResolver             dependencyResolver             = (( GraphDatabaseAPI )db).DependencyResolver;
                    ThreadToStatementContextBridge threadToStatementContextBridge = dependencyResolver.ResolveDependency(typeof(ThreadToStatementContextBridge));
                    KernelTransaction kernelTransaction = threadToStatementContextBridge.GetKernelTransactionBoundToThisThread(true);
                    TokenRead         tokenRead         = kernelTransaction.TokenRead();
                    SchemaRead        schemaRead        = kernelTransaction.SchemaRead();
                    int            labelId    = tokenRead.NodeLabel(TestLabels.LABEL_ONE.name());
                    int            propertyId = tokenRead.PropertyKey("key");
                    IndexReference index      = schemaRead.Index(labelId, propertyId);
                    assertTrue(UnexpectedIndexProviderMessage(index), _schemaIndex.providerName().contains(index.ProviderKey()));
                    assertTrue(UnexpectedIndexProviderMessage(index), _schemaIndex.providerName().contains(index.ProviderVersion()));
                    tx.Success();
                }
            }
            finally
            {
                Db.shutdown();
            }
        }
Exemplo n.º 3
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static java.util.List<java.util.Map<String,Object>> indexes(org.neo4j.internal.kernel.api.TokenRead tokens, org.neo4j.internal.kernel.api.SchemaRead schemaRead, Anonymizer anonymizer) throws org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
        private static IList <IDictionary <string, object> > Indexes(TokenRead tokens, SchemaRead schemaRead, Anonymizer anonymizer)
        {
            IList <IDictionary <string, object> > indexes = new List <IDictionary <string, object> >();

            SilentTokenNameLookup tokenLookup = new SilentTokenNameLookup(tokens);

            IEnumerator <IndexReference> iterator = schemaRead.IndexesGetAll();

            while (iterator.MoveNext())
            {
                IndexReference index = iterator.Current;

                IDictionary <string, object> data = new Dictionary <string, object>();
                data["labels"] = Map(index.Schema().EntityTokenIds, id => anonymizer.Label(tokenLookup.LabelGetName(id), id));

                data["properties"] = Map(index.Schema().PropertyIds, id => anonymizer.PropertyKey(tokenLookup.PropertyKeyGetName(id), id));

                Org.Neo4j.Register.Register_DoubleLongRegister register = Registers.newDoubleLongRegister();
                schemaRead.IndexUpdatesAndSize(index, register);
                data["totalSize"] = register.ReadSecond();
                data["updatesSinceEstimation"] = register.ReadFirst();
                schemaRead.IndexSample(index, register);
                data["estimatedUniqueSize"] = register.ReadFirst();

                indexes.Add(data);
            }

            return(indexes);
        }
Exemplo n.º 4
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private org.neo4j.graphdb.schema.IndexDefinition descriptorToDefinition(final org.neo4j.internal.kernel.api.TokenRead tokenRead, org.neo4j.internal.kernel.api.IndexReference index)
        private IndexDefinition DescriptorToDefinition(TokenRead tokenRead, IndexReference index)
        {
            try
            {
                SchemaDescriptor schema          = index.Schema();
                int[]            entityTokenIds  = Schema.EntityTokenIds;
                bool             constraintIndex = index.Unique;
                string[]         propertyNames   = PropertyNameUtils.GetPropertyKeys(tokenRead, index.Properties());
                switch (Schema.entityType())
                {
                case NODE:
                    Label[] labels = new Label[entityTokenIds.Length];
                    for (int i = 0; i < labels.Length; i++)
                    {
                        labels[i] = label(tokenRead.NodeLabelName(entityTokenIds[i]));
                    }
                    return(new IndexDefinitionImpl(_actions, index, labels, propertyNames, constraintIndex));

                case RELATIONSHIP:
                    RelationshipType[] relTypes = new RelationshipType[entityTokenIds.Length];
                    for (int i = 0; i < relTypes.Length; i++)
                    {
                        relTypes[i] = withName(tokenRead.RelationshipTypeName(entityTokenIds[i]));
                    }
                    return(new IndexDefinitionImpl(_actions, index, relTypes, propertyNames, constraintIndex));

                default:
                    throw new System.ArgumentException("Cannot create IndexDefinition for " + Schema.entityType() + " entity-typed schema.");
                }
            }
            catch (KernelException e)
            {
                throw new Exception(e);
            }
        }
Exemplo n.º 5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void addingANodeWithPropertyShouldGetIndexed() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void AddingANodeWithPropertyShouldGetIndexed()
        {
            // Given
            string indexProperty        = "indexProperty";
            GatheringIndexWriter writer = NewWriter();

            createIndex(_db, _myLabel, indexProperty);

            // When
            int    value1        = 12;
            string otherProperty = "otherProperty";
            int    otherValue    = 17;
            Node   node          = CreateNode(map(indexProperty, value1, otherProperty, otherValue), _myLabel);

            // Then, for now, this should trigger two NodePropertyUpdates
            using (Transaction tx = _db.beginTx())
            {
                KernelTransaction ktx       = _ctxSupplier.getKernelTransactionBoundToThisThread(true);
                TokenRead         tokenRead = ktx.TokenRead();
                int propertyKey1            = tokenRead.PropertyKey(indexProperty);
                int label = tokenRead.NodeLabel(_myLabel.name());
                LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel(label, propertyKey1);
                assertThat(writer.UpdatesCommitted, equalTo(asSet(IndexEntryUpdate.add(node.Id, descriptor, Values.of(value1)))));
                tx.Success();
            }
            // We get two updates because we both add a label and a property to be indexed
            // in the same transaction, in the future, we should optimize this down to
            // one NodePropertyUpdate.
        }
        private void OnTokenRead(uint tokenId)
        {
            lock (this.syncLock)
            {
                var invocationTime = DateTime.Now;
                try
                {
                    if ((invocationTime - lastPublishTime) >= this.deadPeriod)
                    {
                        var tokenIdHash          = hasher.ComputeHash(BitConverter.GetBytes(tokenId));
                        var formattedTokenIdHash = BitConverter.ToString(tokenIdHash).Replace("-", String.Empty);

                        this.logger.Debug($"Relaying token {tokenId} as {formattedTokenIdHash}.");

                        var message = new TokenRead(formattedTokenIdHash);
                        var forget  = this.messagingClient.Publish(message);

                        lastPublishTime = invocationTime;
                    }
                }
                catch (Exception ex)
                {
                    this.logger.Error(ex);
                }
            }
        }
Exemplo n.º 7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static String[] getPropertyKeys(org.neo4j.internal.kernel.api.TokenRead tokenRead, int...properties) throws org.neo4j.internal.kernel.api.exceptions.PropertyKeyIdNotFoundKernelException
        public static string[] GetPropertyKeys(TokenRead tokenRead, params int[] properties)
        {
            string[] propertyKeys = new string[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                propertyKeys[i] = tokenRead.PropertyKeyName(properties[i]);
            }
            return(propertyKeys);
        }
Exemplo n.º 8
0
        internal SchemaCalculator(Transaction ktx)
        {
            this._dataRead  = ktx.DataRead();
            this._tokenRead = ktx.TokenRead();
            this._cursors   = ktx.Cursors();

            // the only one that is common for both nodes and rels so thats why we can do it here
            _propertyIdToPropertyNameMapping = new Dictionary <int, string>(_tokenRead.propertyKeyCount());
            AddNamesToCollection(_tokenRead.propertyKeyGetAllTokens(), _propertyIdToPropertyNameMapping);
        }
Exemplo n.º 9
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static org.neo4j.internal.kernel.api.IndexReference getIndexReference(org.neo4j.internal.kernel.api.SchemaRead schemaRead, org.neo4j.internal.kernel.api.TokenRead tokenRead, IndexDefinitionImpl index) throws org.neo4j.kernel.api.exceptions.schema.SchemaRuleNotFoundException
        private static IndexReference GetIndexReference(SchemaRead schemaRead, TokenRead tokenRead, IndexDefinitionImpl index)
        {
            // Use the precise embedded index reference when available.
            IndexReference reference = index.IndexReference;

            if (reference != null)
            {
                return(reference);
            }

            // Otherwise attempt to reverse engineer the schema that will let us look up the real IndexReference.
            int[]            propertyKeyIds = ResolveAndValidatePropertyKeys(tokenRead, index.PropertyKeysArrayShared);
            SchemaDescriptor schema;

            if (index.NodeIndex)
            {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                int[] labelIds = ResolveAndValidateTokens("Label", index.LabelArrayShared, Label::name, tokenRead.nodeLabel);

                if (index.MultiTokenIndex)
                {
                    schema = multiToken(labelIds, EntityType.NODE, propertyKeyIds);
                }
                else
                {
                    schema = forLabel(labelIds[0], propertyKeyIds);
                }
            }
            else if (index.RelationshipIndex)
            {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                int[] relTypes = ResolveAndValidateTokens("Relationship type", index.RelationshipTypesArrayShared, RelationshipType::name, tokenRead.relationshipType);

                if (index.MultiTokenIndex)
                {
                    schema = multiToken(relTypes, EntityType.RELATIONSHIP, propertyKeyIds);
                }
                else
                {
                    schema = forRelType(relTypes[0], propertyKeyIds);
                }
            }
            else
            {
                throw new System.ArgumentException("The given index is neither a node index, nor a relationship index: " + index + ".");
            }

            reference = schemaRead.Index(schema);
            if (reference == IndexReference.NO_INDEX)
            {
                throw new SchemaRuleNotFoundException(Org.Neo4j.Storageengine.Api.schema.SchemaRule_Kind.IndexRule, schema);
            }

            return(reference);
        }
Exemplo n.º 10
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void putTokenCounts(java.util.Map<String,Object> metaData, org.neo4j.internal.kernel.api.Kernel kernel) throws org.neo4j.internal.kernel.api.exceptions.TransactionFailureException
        internal static void PutTokenCounts(IDictionary <string, object> metaData, Kernel kernel)
        {
            using (Transaction tx = kernel.BeginTransaction([email protected]_Type.Explicit, LoginContext.AUTH_DISABLED))
            {
                TokenRead tokens = tx.TokenRead();
                metaData["labelCount"]            = tokens.LabelCount();
                metaData["relationshipTypeCount"] = tokens.RelationshipTypeCount();
                metaData["propertyKeyCount"]      = tokens.PropertyKeyCount();
                tx.Success();
            }
        }
Exemplo n.º 11
0
        private void AssertCorrectProvider(GraphDatabaseAPI db, Label label, string property)
        {
            KernelTransaction kernelTransaction = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge)).getKernelTransactionBoundToThisThread(false);
            TokenRead         tokenRead         = kernelTransaction.TokenRead();
            int            labelId    = tokenRead.NodeLabel(label.Name());
            int            propId     = tokenRead.PropertyKey(property);
            SchemaRead     schemaRead = kernelTransaction.SchemaRead();
            IndexReference index      = schemaRead.Index(labelId, propId);

            assertEquals("correct provider key", "lucene+native", index.ProviderKey());
            assertEquals("correct provider version", "1.0", index.ProviderVersion());
        }
Exemplo n.º 12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setup()
        public virtual void Setup()
        {
            _transaction   = mock(typeof(KernelTransaction));
            _tokenRead     = mock(typeof(TokenRead));
            _schemaRead    = mock(typeof(SchemaRead));
            _procedure     = new IndexProcedures(_transaction, null);
            _descriptor    = SchemaDescriptorFactory.forLabel(123, 456);
            _anyDescriptor = SchemaDescriptorFactory.forLabel(0, 0);
            _anyIndex      = forSchema(_anyDescriptor);
            when(_transaction.tokenRead()).thenReturn(_tokenRead);
            when(_transaction.schemaRead()).thenReturn(_schemaRead);
        }
Exemplo n.º 13
0
        private void RelayTokenReadMessage(Object sender, TokenRead message)
        {
            try
            {
                this.logger.Debug($"Relaying {nameof(TokenRead)} message: {message.Id}");

                this.callBack?.OnTokenReadPublished(message);
            }
            catch (Exception exception)
            {
                this.logger.Error(exception);
            }
        }
Exemplo n.º 14
0
        public override IDictionary <string, object> GetProperties(params string[] keys)
        {
            Objects.requireNonNull(keys, "Properties keys should be not null array.");

            if (keys.Length == 0)
            {
                return(Collections.emptyMap());
            }

            KernelTransaction transaction = SafeAcquireTransaction();

            int itemsToReturn = keys.Length;
            IDictionary <string, object> properties = new Dictionary <string, object>(itemsToReturn);
            TokenRead token = transaction.TokenRead();

            //Find ids, note we are betting on that the number of keys
            //is small enough not to use a set here.
            int[] propertyIds = new int[itemsToReturn];
            for (int i = 0; i < itemsToReturn; i++)
            {
                string key = keys[i];
                if (string.ReferenceEquals(key, null))
                {
                    throw new System.NullReferenceException(string.Format("Key {0:D} was null", i));
                }
                propertyIds[i] = token.PropertyKey(key);
            }

            NodeCursor     nodes          = transaction.AmbientNodeCursor();
            PropertyCursor propertyCursor = transaction.AmbientPropertyCursor();

            SingleNode(transaction, nodes);
            nodes.Properties(propertyCursor);
            int propertiesToFind = itemsToReturn;

            while (propertiesToFind > 0 && propertyCursor.Next())
            {
                //Do a linear check if this is a property we are interested in.
                int currentKey = propertyCursor.PropertyKey();
                for (int i = 0; i < itemsToReturn; i++)
                {
                    if (propertyIds[i] == currentKey)
                    {
                        properties[keys[i]] = propertyCursor.PropertyValue().asObjectCopy();
                        propertiesToFind--;
                        break;
                    }
                }
            }
            return(properties);
        }
Exemplo n.º 15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static java.util.stream.Stream<RetrieveResult> retrieve(org.neo4j.internal.kernel.api.Kernel kernel, Anonymizer anonymizer) throws org.neo4j.internal.kernel.api.exceptions.TransactionFailureException, org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
        internal static Stream <RetrieveResult> Retrieve(Kernel kernel, Anonymizer anonymizer)
        {
            using (Transaction tx = kernel.BeginTransaction([email protected]_Type.Explicit, LoginContext.AUTH_DISABLED))
            {
                TokenRead tokens = tx.TokenRead();
                Read      read   = tx.DataRead();

                IDictionary <string, object> data = new Dictionary <string, object>();
                data["nodes"]         = NodeCounts(tokens, read, anonymizer);
                data["relationships"] = RelationshipCounts(tokens, read, anonymizer);
                data["indexes"]       = Indexes(tokens, tx.SchemaRead(), anonymizer);
                data["constraints"]   = Constraints(tokens, tx.SchemaRead(), anonymizer);

                return(Stream.of(new RetrieveResult(Sections.GRAPH_COUNTS, data)));
            }
        }
        private IDictionary <string, int> GetLabelIdsByName(params string[] names)
        {
            ThreadToStatementContextBridge transactionStatementContextBridge = TransactionStatementContextBridge;
            IDictionary <string, int>      labelNameIdMap = new Dictionary <string, int>();
            KernelTransaction ktx = transactionStatementContextBridge.GetKernelTransactionBoundToThisThread(true);

            using (Statement ignore = ktx.AcquireStatement())
            {
                TokenRead tokenRead = ktx.TokenRead();
                foreach (string name in names)
                {
                    labelNameIdMap[name] = tokenRead.NodeLabel(name);
                }
            }
            return(labelNameIdMap);
        }
Exemplo n.º 17
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertIndexProvider(org.neo4j.graphdb.GraphDatabaseService db, String expectedProviderIdentifier) throws org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
        private void AssertIndexProvider(GraphDatabaseService db, string expectedProviderIdentifier)
        {
            GraphDatabaseAPI graphDatabaseAPI = ( GraphDatabaseAPI )db;

            using (Transaction tx = graphDatabaseAPI.BeginTx())
            {
                KernelTransaction ktx       = graphDatabaseAPI.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge)).getKernelTransactionBoundToThisThread(true);
                TokenRead         tokenRead = ktx.TokenRead();
                int            labelId      = tokenRead.NodeLabel(LABEL.name());
                int            propertyId   = tokenRead.PropertyKey(KEY);
                IndexReference index        = ktx.SchemaRead().index(labelId, propertyId);

                assertEquals("expected IndexProvider.Descriptor", expectedProviderIdentifier, (new IndexProviderDescriptor(index.ProviderKey(), index.ProviderVersion())).name());
                tx.Success();
            }
        }
Exemplo n.º 18
0
        public virtual IEnumerable <ConstraintDefinition> getConstraints(RelationshipType type)
        {
            KernelTransaction transaction = SafeAcquireTransaction(_transactionSupplier);

            using (Statement ignore = transaction.AcquireStatement())
            {
                TokenRead  tokenRead  = transaction.TokenRead();
                SchemaRead schemaRead = transaction.SchemaRead();
                int        typeId     = tokenRead.RelationshipType(type.Name());
                if (typeId == [email protected]_Fields.NO_TOKEN)
                {
                    return(emptyList());
                }
                return(AsConstraintDefinitions(schemaRead.ConstraintsGetForRelationshipType(typeId), tokenRead));
            }
        }
Exemplo n.º 19
0
        private static IList <IDictionary <string, object> > NodeCounts(TokenRead tokens, Read read, Anonymizer anonymizer)
        {
            IList <IDictionary <string, object> > nodeCounts = new List <IDictionary <string, object> >();
            IDictionary <string, object>          nodeCount  = new Dictionary <string, object>();

            nodeCount["count"] = read.CountsForNodeWithoutTxState(-1);
            nodeCounts.Add(nodeCount);

            tokens.LabelsGetAllTokens().forEachRemaining(t =>
            {
                long count = read.CountsForNodeWithoutTxState(t.id());
                IDictionary <string, object> labelCount = new Dictionary <string, object>();
                labelCount.put("label", anonymizer.Label(t.name(), t.id()));
                labelCount.put("count", count);
                nodeCounts.Add(labelCount);
            });

            return(nodeCounts);
        }
Exemplo n.º 20
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: public Iterable<org.neo4j.graphdb.schema.IndexDefinition> getIndexes(final org.neo4j.graphdb.Label label)
        public override IEnumerable <IndexDefinition> GetIndexes(Label label)
        {
            KernelTransaction transaction = _transactionSupplier.get();

            using (Statement ignore = transaction.AcquireStatement())
            {
                TokenRead  tokenRead  = transaction.TokenRead();
                SchemaRead schemaRead = transaction.SchemaRead();
                IList <IndexDefinition> definitions = new List <IndexDefinition>();
                int labelId = tokenRead.NodeLabel(label.Name());
                if (labelId == [email protected]_Fields.NO_TOKEN)
                {
                    return(emptyList());
                }
                IEnumerator <IndexReference> indexes = schemaRead.IndexesGetForLabel(labelId);
                AddDefinitions(definitions, tokenRead, IndexReference.sortByType(indexes));
                return(definitions);
            }
        }
Exemplo n.º 21
0
        private static IList <IDictionary <string, object> > RelationshipCounts(TokenRead tokens, Read read, Anonymizer anonymizer)
        {
            IList <IDictionary <string, object> > relationshipCounts = new List <IDictionary <string, object> >();
            IDictionary <string, object>          relationshipCount  = new Dictionary <string, object>();

            relationshipCount["count"] = read.CountsForRelationshipWithoutTxState(-1, -1, -1);
            relationshipCounts.Add(relationshipCount);

            IList <NamedToken> labels = Iterators.asList(tokens.LabelsGetAllTokens());

            tokens.RelationshipTypesGetAllTokens().forEachRemaining(t =>
            {
                long count = read.CountsForRelationshipWithoutTxState(-1, t.id(), -1);
                IDictionary <string, object> relationshipTypeCount = new Dictionary <string, object>();
                relationshipTypeCount.put("relationshipType", anonymizer.RelationshipType(t.name(), t.id()));
                relationshipTypeCount.put("count", count);
                relationshipCounts.Add(relationshipTypeCount);
                foreach (NamedToken label in labels)
                {
                    long startCount = read.CountsForRelationshipWithoutTxState(label.id(), t.id(), -1);
                    if (startCount > 0)
                    {
                        IDictionary <string, object> x = new Dictionary <string, object>();
                        x.put("relationshipType", anonymizer.RelationshipType(t.name(), t.id()));
                        x.put("startLabel", anonymizer.Label(label.name(), label.id()));
                        x.put("count", startCount);
                        relationshipCounts.Add(x);
                    }
                    long endCount = read.CountsForRelationshipWithoutTxState(-1, t.id(), label.id());
                    if (endCount > 0)
                    {
                        IDictionary <string, object> x = new Dictionary <string, object>();
                        x.put("relationshipType", anonymizer.RelationshipType(t.name(), t.id()));
                        x.put("endLabel", anonymizer.Label(label.name(), label.id()));
                        x.put("count", endCount);
                        relationshipCounts.Add(x);
                    }
                }
            });

            return(relationshipCounts);
        }
Exemplo n.º 22
0
        private int[] RelTypeIds(RelationshipType[] types, TokenRead token)
        {
            int[] ids      = new int[types.Length];
            int   outIndex = 0;

            foreach (RelationshipType type in types)
            {
                int id = token.RelationshipType(type.Name());
                if (id != NO_SUCH_RELATIONSHIP_TYPE)
                {
                    ids[outIndex++] = id;
                }
            }

            if (outIndex != ids.Length)
            {
                // One or more relationship types do not exist, so we can exclude them right away.
                ids = Arrays.copyOf(ids, outIndex);
            }
            return(ids);
        }
Exemplo n.º 23
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static java.util.stream.Stream<RetrieveResult> retrieve(org.neo4j.internal.kernel.api.Kernel kernel) throws org.neo4j.internal.kernel.api.exceptions.TransactionFailureException
        internal static Stream <RetrieveResult> Retrieve(Kernel kernel)
        {
            using (Transaction tx = kernel.BeginTransaction([email protected]_Type.Explicit, LoginContext.AUTH_DISABLED))
            {
                TokenRead tokens = tx.TokenRead();

                IList <string> labels = new List <string>(tokens.LabelCount());
                tokens.LabelsGetAllTokens().forEachRemaining(t => labels.Add(t.name()));

                IList <string> relationshipTypes = new List <string>(tokens.RelationshipTypeCount());
                tokens.RelationshipTypesGetAllTokens().forEachRemaining(t => relationshipTypes.Add(t.name()));

                IList <string> propertyKeys = new List <string>(tokens.PropertyKeyCount());
                tokens.PropertyKeyGetAllTokens().forEachRemaining(t => propertyKeys.Add(t.name()));

                IDictionary <string, object> data = new Dictionary <string, object>();
                data["labels"]            = labels;
                data["relationshipTypes"] = relationshipTypes;
                data["propertyKeys"]      = propertyKeys;
                return(Stream.of(new RetrieveResult(Sections.TOKENS, data)));
            }
        }
        public async void Handle(TokenRead message)
        {
            // TODO: Play success beep

            try
            {
                if (this.navigationService.CurrentSourcePageType != typeof(StartView))
                {
                    this.toastService.Show("A fob was read and ignored.", "To sign-in with it go BACK to the first screen and try again.");
                }
                else
                {
                    var tokenHolder = await this.tokenHolderService.GetTokenHolderByTokenId(message.Id);

                    if (tokenHolder == null)
                    {
                        this.navigationService.NavigateToViewModel <NameEntryViewModel>(message.Id);
                    }
                    else
                    {
                        SignedInRecord signedInRecord;
                        if (this.signInService.TryGetSignedInRecord(tokenHolder.TokenId, out signedInRecord))
                        {
                            await this.signInService.RequestSignOut(signedInRecord);
                        }
                        else
                        {
                            await this.signInService.RequestSignIn(tokenHolder);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // TODO: log error
                this.toastService.ShowGenericError();
            }
        }
Exemplo n.º 25
0
            public override void DropNodePropertyExistenceConstraint(Label label, string[] properties)
            {
                KernelTransaction transaction = SafeAcquireTransaction(TransactionSupplier);

                using (Statement ignore = transaction.AcquireStatement())
                {
                    try
                    {
                        TokenRead tokenRead      = transaction.TokenRead();
                        int       labelId        = tokenRead.NodeLabel(label.Name());
                        int[]     propertyKeyIds = ResolveAndValidatePropertyKeys(tokenRead, properties);
                        transaction.SchemaWrite().constraintDrop(ConstraintDescriptorFactory.existsForLabel(labelId, propertyKeyIds));
                    }
                    catch (DropConstraintFailureException e)
                    {
                        throw new ConstraintViolationException(e.GetUserMessage(new SilentTokenNameLookup(transaction.TokenRead())), e);
                    }
                    catch (Exception e) when(e is InvalidTransactionTypeKernelException || e is SchemaKernelException)
                    {
                        throw new ConstraintViolationException(e.Message, e);
                    }
                }
            }
Exemplo n.º 26
0
        private static IList <IDictionary <string, object> > Constraints(TokenRead tokens, SchemaRead schemaRead, Anonymizer anonymizer)
        {
            IList <IDictionary <string, object> > constraints = new List <IDictionary <string, object> >();

            SilentTokenNameLookup tokenLookup = new SilentTokenNameLookup(tokens);

            IEnumerator <ConstraintDescriptor> iterator = schemaRead.ConstraintsGetAll();

            while (iterator.MoveNext())
            {
                ConstraintDescriptor         constraint = iterator.Current;
                EntityType                   entityType = constraint.Schema().entityType();
                IDictionary <string, object> data       = new Dictionary <string, object>();

                data["properties"] = Map(constraint.Schema().PropertyIds, id => anonymizer.PropertyKey(tokenLookup.PropertyKeyGetName(id), id));
                data["type"]       = ConstraintType(constraint);
                int entityTokenId = constraint.Schema().EntityTokenIds[0];

                switch (entityType.innerEnumValue)
                {
                case EntityType.InnerEnum.NODE:
                    data["label"] = anonymizer.Label(tokenLookup.LabelGetName(entityTokenId), entityTokenId);
                    constraints.Add(data);
                    break;

                case EntityType.InnerEnum.RELATIONSHIP:
                    data["relationshipType"] = anonymizer.RelationshipType(tokenLookup.RelationshipTypeGetName(entityTokenId), entityTokenId);
                    constraints.Add(data);
                    break;

                default:
                    break;
                }
            }

            return(constraints);
        }
Exemplo n.º 27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void addingALabelToPreExistingNodeShouldGetIndexed() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void AddingALabelToPreExistingNodeShouldGetIndexed()
        {
            // GIVEN
            string indexProperty        = "indexProperty";
            GatheringIndexWriter writer = NewWriter();

            createIndex(_db, _myLabel, indexProperty);

            // WHEN
            string otherProperty = "otherProperty";
            int    value         = 12;
            int    otherValue    = 17;
            Node   node          = CreateNode(map(indexProperty, value, otherProperty, otherValue));

            // THEN
            assertThat(writer.UpdatesCommitted.Count, equalTo(0));

            // AND WHEN
            using (Transaction tx = _db.beginTx())
            {
                node.AddLabel(_myLabel);
                tx.Success();
            }

            // THEN
            using (Transaction tx = _db.beginTx())
            {
                KernelTransaction ktx       = _ctxSupplier.getKernelTransactionBoundToThisThread(true);
                TokenRead         tokenRead = ktx.TokenRead();
                int propertyKey1            = tokenRead.PropertyKey(indexProperty);
                int label = tokenRead.NodeLabel(_myLabel.name());
                LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel(label, propertyKey1);
                assertThat(writer.UpdatesCommitted, equalTo(asSet(IndexEntryUpdate.add(node.Id, descriptor, Values.of(value)))));
                tx.Success();
            }
        }
Exemplo n.º 28
0
            public override void DropRelationshipPropertyExistenceConstraint(RelationshipType type, string propertyKey)
            {
                KernelTransaction transaction = SafeAcquireTransaction(TransactionSupplier);

                using (Statement ignore = transaction.AcquireStatement())
                {
                    try
                    {
                        TokenRead tokenRead = transaction.TokenRead();

                        int typeId        = tokenRead.RelationshipType(type.Name());
                        int propertyKeyId = tokenRead.PropertyKey(propertyKey);
                        transaction.SchemaWrite().constraintDrop(ConstraintDescriptorFactory.existsForRelType(typeId, propertyKeyId));
                    }
                    catch (DropConstraintFailureException e)
                    {
                        throw new ConstraintViolationException(e.GetUserMessage(new SilentTokenNameLookup(transaction.TokenRead())), e);
                    }
                    catch (Exception e) when(e is InvalidTransactionTypeKernelException || e is SchemaKernelException)
                    {
                        throw new ConstraintViolationException(e.Message, e);
                    }
                }
            }
 public async void OnTokenReadPublished(TokenRead message)
 {
     await this.eventAggregator.PublishOnUIThreadAsync(message);
 }
Exemplo n.º 30
0
        private ConstraintDefinition AsConstraintDefinition(ConstraintDescriptor constraint, TokenRead tokenRead)
        {
            // This was turned inside out. Previously a low-level constraint object would reference a public enum type
            // which made it impossible to break out the low-level component from kernel. There could be a lower level
            // constraint type introduced to mimic the public ConstraintType, but that would be a duplicate of it
            // essentially. Checking instanceof here is OKish since the objects it checks here are part of the
            // internal storage engine API.
            SilentTokenNameLookup lookup = new SilentTokenNameLookup(tokenRead);

            if (constraint is NodeExistenceConstraintDescriptor || constraint is NodeKeyConstraintDescriptor || constraint is UniquenessConstraintDescriptor)
            {
                SchemaDescriptor schemaDescriptor = constraint.Schema();
                int[]            entityTokenIds   = schemaDescriptor.EntityTokenIds;
                Label[]          labels           = new Label[entityTokenIds.Length];
                for (int i = 0; i < entityTokenIds.Length; i++)
                {
                    labels[i] = label(lookup.LabelGetName(entityTokenIds[i]));
                }
//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
                string[] propertyKeys = Arrays.stream(schemaDescriptor.PropertyIds).mapToObj(lookup.propertyKeyGetName).toArray(string[] ::new);
                if (constraint is NodeExistenceConstraintDescriptor)
                {
                    return(new NodePropertyExistenceConstraintDefinition(_actions, labels[0], propertyKeys));
                }
                else if (constraint is UniquenessConstraintDescriptor)
                {
                    return(new UniquenessConstraintDefinition(_actions, new IndexDefinitionImpl(_actions, null, labels, propertyKeys, true)));
                }
                else
                {
                    return(new NodeKeyConstraintDefinition(_actions, new IndexDefinitionImpl(_actions, null, labels, propertyKeys, true)));
                }
            }
            else if (constraint is RelExistenceConstraintDescriptor)
            {
                RelationTypeSchemaDescriptor descriptor = ( RelationTypeSchemaDescriptor )constraint.Schema();
                return(new RelationshipPropertyExistenceConstraintDefinition(_actions, withName(lookup.RelationshipTypeGetName(descriptor.RelTypeId)), lookup.PropertyKeyGetName(descriptor.PropertyId)));
            }
            throw new System.ArgumentException("Unknown constraint " + constraint);
        }