示例#1
0
        public void SparqlUpdateDeleteWithBind()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromFile("resources\\rvesse.ttl");
            store.Add(g);

            int origTriples = g.Triples.Count;

            SparqlParameterizedString command = new SparqlParameterizedString();

            command.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/"));
            command.CommandText = "DELETE { ?x foaf:mbox ?y } WHERE { ?x foaf:mbox ?email . BIND(?email AS ?y) }";

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(command);

            InMemoryDataset          dataset   = new InMemoryDataset(store, g.BaseUri);
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            processor.ProcessCommandSet(cmds);

            Assert.NotEqual(origTriples, g.Triples.Count);
            Assert.False(g.GetTriplesWithPredicate(g.CreateUriNode(new Uri("http://xmlns.com/foaf/0.1/mbox"))).Any(), "Expected triples to have been deleted");
        }
示例#2
0
        public void SparqlUpdateInsertCommand3()
        {
            SparqlParameterizedString command = new SparqlParameterizedString();

            command.Namespaces.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));
            command.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS));
            command.CommandText  = "INSERT { ?s rdf:type ?class } USING NAMED <http://example.org/temp> WHERE { ?s a ?type . ?type rdfs:subClassOf+ ?class };";
            command.CommandText += "INSERT { ?s ?property ?value } USING NAMED <http://example.org/temp> WHERE {?s ?p ?value . ?p rdfs:subPropertyOf+ ?property };";
            command.CommandText += "INSERT { ?s rdf:type rdfs:Class } USING NAMED <http://example.org/temp> WHERE { ?s rdfs:subClassOf ?class };";
            command.CommandText += "INSERT { ?s rdf:type rdf:Property } USING NAMED <http://example.org/temp> WHERE { ?s rdfs:subPropertyOf ?property };";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            g.BaseUri = new Uri("http://example.org/temp");
            store.Add(g);

            SparqlUpdateParser       parser    = new SparqlUpdateParser();
            SparqlUpdateCommandSet   cmds      = parser.ParseFromString(command);
            InMemoryDataset          dataset   = new InMemoryDataset(store);
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            dataset.SetDefaultGraph((Uri)null);
            processor.ProcessCommandSet(cmds);

            IGraph def = store[null];

            TestTools.ShowGraph(def);
            Assert.IsTrue(def.IsEmpty, "Graph should be empty as the commands only used USING NAMED (so shouldn't have changed the dataset) and the Active Graph for the dataset was empty so there should have been nothing matched to generate insertions from");
        }
示例#3
0
        /// <summary>
        /// Executes a SPARQL Update on the Store
        /// </summary>
        /// <param name="update">SPARQL Update</param>
        /// <remarks>
        /// <para>
        /// If the underlying Manager is an <see cref="IUpdateableGenericIOManager">IUpdateableGenericIOManager</see> then the managers own Update implementation will be used, otherwise dotNetRDF's approximated implementation for generic stores will be used.  In the case of approximation exact feature support will vary depending on the underlying manager being used.
        /// </para>
        /// </remarks>
        public void ExecuteUpdate(string update)
        {
            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(update);

            this.ExecuteUpdate(cmds);
        }
示例#4
0
        public void SparqlUpdateInsertWithBind()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromFile("rvesse.ttl");
            store.Add(g);

            int origTriples = g.Triples.Count;

            SparqlParameterizedString command = new SparqlParameterizedString();

            command.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/"));
            command.CommandText = "INSERT { ?x foaf:mbox_sha1sum ?hash } WHERE { ?x foaf:mbox ?email . BIND(SHA1(STR(?email)) AS ?hash) }";

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(command);

            InMemoryDataset          dataset   = new InMemoryDataset(store, g.BaseUri);
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            processor.ProcessCommandSet(cmds);

            Assert.AreNotEqual(origTriples, g.Triples.Count, "Expected new triples to have been added");
            Assert.IsTrue(g.GetTriplesWithPredicate(g.CreateUriNode(new Uri("http://xmlns.com/foaf/0.1/mbox_sha1sum"))).Any(), "Expected new triples to have been added");
        }
示例#5
0
        public void SparqlUpdateDeleteWithFilter()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromFile("rvesse.ttl");
            store.Add(g);

            int origTriples = g.Triples.Count;

            SparqlParameterizedString command = new SparqlParameterizedString();

            command.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/"));
            command.CommandText = "DELETE { ?x foaf:mbox ?email } WHERE { ?x foaf:mbox ?email . FILTER(REGEX(STR(?email), 'dotnetrdf\\.org')) }";

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(command);

            InMemoryDataset          dataset   = new InMemoryDataset(store, g.BaseUri);
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            processor.ProcessCommandSet(cmds);

            Assert.AreNotEqual(origTriples, g.Triples.Count, "Expected triples to have been deleted");
            Assert.IsFalse(g.GetTriplesWithPredicate(g.CreateUriNode(new Uri("http://xmlns.com/foaf/0.1/mbox"))).Where(t => t.Object.ToString().Contains("dotnetrdf.org")).Any(), "Expected triples to have been deleted");
        }
示例#6
0
        public void SparqlUpdate()
        {
            TripleStore        store  = new TripleStore();
            SparqlUpdateParser parser = new SparqlUpdateParser();

            //Generate a Command
            SparqlParameterizedString cmdString = new SparqlParameterizedString();

            cmdString.CommandText = "LOAD <http://dbpedia.org/resource/Southampton> INTO <http://example.org/Soton>";

            //Parse the command into a SparqlUpdateCommandSet
            SparqlUpdateCommandSet cmds = parser.ParseFromString(cmdString);

            //Create an Update Processor using our dataset and apply the updates
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);

            processor.ProcessCommandSet(cmds);

            //We should now have a Graph in our dataset as a result of the LOAD update
            //So we'll retrieve this and print it to the Console
            IGraph            g         = store.Graphs[new Uri("http://example.org/Soton")];
            NTriplesFormatter formatter = new NTriplesFormatter();

            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString(formatter));
            }
        }
示例#7
0
        public void SparqlUpdateCopyCommand3()
        {
            IGraph g = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            g.BaseUri = null;

            IGraph h = new Graph();

            FileLoader.Load(h, "Turtle.ttl");
            h.BaseUri = new Uri("http://example.org/destination");

            TripleStore store = new TripleStore();

            store.Add(g);
            store.Add(h);

            Assert.AreNotEqual(g, h, "Graphs should not be equal");

            SparqlUpdateParser     parser   = new SparqlUpdateParser();
            SparqlUpdateCommandSet commands = parser.ParseFromString("COPY DEFAULT TO GRAPH <http://example.org/destination>");

            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);

            processor.ProcessCommandSet(commands);

            g = store[null];
            h = store[new Uri("http://example.org/destination")];
            Assert.IsFalse(g.IsEmpty, "Source Graph should not be empty");
            Assert.IsFalse(h.IsEmpty, "Destination Graph should not be empty");
            Assert.AreEqual(g, h, "Graphs should now be equal");
        }
        public void SparqlParsingUpdateWithDeleteWhereIllegal()
        {
            const string       update = "WITH <http://graph> DELETE WHERE { ?s ?p ?o }";
            SparqlUpdateParser parser = new SparqlUpdateParser();

            Assert.Throws <RdfParseException>(() => parser.ParseFromString(update));
        }
示例#9
0
        /// <summary>
        /// Executes an Update against the Triple Store
        /// </summary>
        /// <param name="update">SPARQL Update Command(s)</param>
        /// <remarks>
        /// As per the SPARQL 1.1 Update specification the command string may be a sequence of commands
        /// </remarks>
        public void ExecuteUpdate(string update)
        {
            SparqlUpdateParser     parser     = new SparqlUpdateParser();
            SparqlUpdateCommandSet commandSet = parser.ParseFromString(update);

            ExecuteUpdate(commandSet);
        }
示例#10
0
        public void SparqlUpdateAddCommand2()
        {
            IGraph g = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            g.BaseUri = new Uri("http://example.org/source");

            IGraph h = new Graph();

            FileLoader.Load(h, "Turtle.ttl");
            h.BaseUri = null;

            TripleStore store = new TripleStore();

            store.Add(g);
            store.Add(h);

            Assert.AreNotEqual(g, h, "Graphs should not be equal");

            SparqlUpdateParser     parser   = new SparqlUpdateParser();
            SparqlUpdateCommandSet commands = parser.ParseFromString("ADD GRAPH <http://example.org/source> TO DEFAULT");

            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);

            processor.ProcessCommandSet(commands);

            g = store[new Uri("http://example.org/source")];
            h = store[null];
            Assert.IsFalse(g.IsEmpty, "Source Graph should not be empty");
            Assert.IsFalse(h.IsEmpty, "Destination Graph should not be empty");
            Assert.IsTrue(h.HasSubGraph(g), "Destination Graph should have Source Graph as a subgraph");
        }
        public void SparqlUpdateDeleteCommandWithNoMatchingGraphAndChildGraphPatterns()
        {
            var dataset        = new InMemoryDataset();
            var updateGraphUri = new Uri("http://example.org/g2");
            var updateGraph    = new Graph {
                BaseUri = updateGraphUri
            };

            updateGraph.Assert(new Triple(updateGraph.CreateUriNode(new Uri("http://example.org/s")),
                                          updateGraph.CreateUriNode(new Uri("http://example.org/p")),
                                          updateGraph.CreateUriNode(new Uri("http://example.org/o"))));
            dataset.AddGraph(updateGraph);

            var egGraph = new Uri("http://example.org/graph");

            dataset.HasGraph(egGraph).Should().BeFalse();
            var processor = new LeviathanUpdateProcessor(dataset);
            var cmdSet    = new SparqlUpdateParser().ParseFromString(
                "WITH <" + egGraph +
                "> DELETE { GRAPH <http://example.org/g2> { <http://example.org/s> <http://example.org/p> <http://example.org/o> }} WHERE {}");

            processor.ProcessCommandSet(cmdSet);

            dataset.HasGraph(egGraph).Should().BeFalse(because: "Update command should not create an empty graph for a DELETE operation");
            dataset[updateGraphUri].IsEmpty.Should()
            .BeTrue("Triples should be deleted by child graph pattern");
        }
示例#12
0
        /// <summary>
        /// Executes an Update against the Triple Store.
        /// </summary>
        /// <param name="update">SPARQL Update Command(s).</param>
        /// <remarks>
        /// As per the SPARQL 1.1 Update specification the command string may be a sequence of commands.
        /// </remarks>
        public void ExecuteUpdate(string update)
        {
            if (_manager is IUpdateableStorage)
            {
                if (!((PersistentGraphCollection)_graphs).IsSynced)
                {
                    throw new SparqlUpdateException("Unable to execute a SPARQL Update as the in-memory view of the store is not synced with the underlying store, please invoked Flush() or Discard() and try again.  Alternatively if you do not want to see in-memory changes reflected in update results you can invoke the Update() method directly on the underlying store by accessing it through the UnderlyingStore property.");
                }

                ((IUpdateableStorage)_manager).Update(update);
            }
            else
            {
                if (_updateProcessor == null)
                {
                    _updateProcessor = new GenericUpdateProcessor(_manager);
                }
                if (_updateParser == null)
                {
                    _updateParser = new SparqlUpdateParser();
                }
                SparqlUpdateCommandSet cmds = _updateParser.ParseFromString(update);
                _updateProcessor.ProcessCommandSet(cmds);
            }
        }
示例#13
0
        public void SparqlUpdateDeleteWithGraphClause1()
        {
            Graph g = new Graph();

            g.Assert(g.CreateUriNode(UriFactory.Create("http://subject")), g.CreateUriNode(UriFactory.Create("http://predicate")), g.CreateUriNode(UriFactory.Create("http://object")));
            Graph h = new Graph();

            h.Merge(g);
            h.BaseUri = UriFactory.Create("http://subject");

            InMemoryDataset dataset = new InMemoryDataset(g);

            dataset.AddGraph(h);
            dataset.Flush();

            Assert.AreEqual(2, dataset.GraphUris.Count());

            String updates = "DELETE { GRAPH ?s { ?s ?p ?o } } WHERE { ?s ?p ?o }";
            SparqlUpdateCommandSet commands = new SparqlUpdateParser().ParseFromString(updates);

            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            processor.ProcessCommandSet(commands);

            Assert.AreEqual(2, dataset.GraphUris.Count());
            Assert.IsTrue(dataset.HasGraph(UriFactory.Create("http://subject")));
            Assert.AreEqual(0, dataset[UriFactory.Create("http://subject")].Triples.Count);
        }
示例#14
0
        internal IEnumerable <IUpdate> BuildUpdate(String sparqlQuery)
        {
            List <IUpdate>         spinQueryList = new List <IUpdate>();
            SparqlUpdateCommandSet query         = new SparqlUpdateParser().ParseFromString(sparqlQuery);

            query.Optimise();
            foreach (SparqlUpdateCommand command in query.Commands)
            {
                sparqlQuery = command.ToString();
                if (queryCache.ContainsKey(sparqlQuery))
                {
                    spinQueryList.Add((IUpdate)queryCache[sparqlQuery]);
                }
                else
                {
                    _currentSparqlGraph         = new Graph();
                    _currentSparqlGraph.BaseUri = UriFactory.Create("sparql-query:" + sparqlQuery);
                    INode q = command.ToSpinRdf(_currentSparqlGraph);
                    if (!_currentSparqlGraph.IsEmpty)
                    {
                        _spinConfiguration.AddGraph(_currentSparqlGraph);
                        IUpdate spinQuery = SPINFactory.asUpdate(Resource.Get(q, this));
                        queryCache[sparqlQuery] = spinQuery;
                        spinQueryList.Add(spinQuery);
                    }
                }
            }
            return(spinQueryList);
        }
示例#15
0
        public void SparqlUpdateInsertDataCombination()
        {
            SparqlParameterizedString command = new SparqlParameterizedString();

            command.Namespaces.AddNamespace("ex", new Uri("http://example.org/"));
            command.CommandText = "INSERT DATA { ex:a ex:b ex:c GRAPH <http://example.org/graph> { ex:a ex:b ex:c } }";

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(command);

            Assert.IsFalse(cmds.Commands.All(cmd => cmd.AffectsSingleGraph), "Commands should report that they do not affect a single Graph");
            Assert.IsTrue(cmds.Commands.All(cmd => cmd.AffectsGraph(null)), "Commands should report that they affect the Default Graph");
            Assert.IsTrue(cmds.Commands.All(cmd => cmd.AffectsGraph(new Uri("http://example.org/graph"))), "Commands should report that they affect the named Graph");

            InMemoryDataset          dataset   = new InMemoryDataset();
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            processor.ProcessCommandSet(cmds);

            Graph g = new Graph();

            g.NamespaceMap.Import(command.Namespaces);
            Triple t = new Triple(g.CreateUriNode("ex:a"), g.CreateUriNode("ex:b"), g.CreateUriNode("ex:c"));

            IGraph def = dataset[null];

            Assert.AreEqual(1, def.Triples.Count, "Should be 1 Triple in the Default Graph");
            Assert.IsTrue(def.ContainsTriple(t), "Should have the inserted Triple in the Default Graph");

            IGraph ex = dataset[new Uri("http://example.org/graph")];

            Assert.AreEqual(1, ex.Triples.Count, "Should be 1 Triple in the Named Graph");
            Assert.IsTrue(ex.ContainsTriple(t), "Should have the inserted Triple in the Named Graph");
        }
示例#16
0
        protected override TaskResult RunTaskInternal()
        {
            SparqlUpdateParser parser = new SparqlUpdateParser();

            this._cmds = parser.ParseFromString(this._update);
            GenericUpdateProcessor processor = new GenericUpdateProcessor(this._manager);

            processor.ProcessCommandSet(this._cmds);
            return(new TaskResult(true));
        }
示例#17
0
        public void SparqlUpdateDeleteWithCommand()
        {
            String                 command = "WITH <http://example.org/> DELETE { ?s ?p ?o } WHERE {?s ?p ?o}";
            SparqlUpdateParser     parser  = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds    = parser.ParseFromString(command);

            DeleteCommand delete = (DeleteCommand)cmds[0];

            Assert.AreEqual(new Uri("http://example.org/"), delete.GraphUri, "Graph URI of the Command should be equal to http://example.org/");
        }
示例#18
0
        /// <summary>
        /// Executes this command as an update
        /// </summary>
        public void ExecuteUpdate()
        {
            if (this._updateProcessor == null)
            {
                throw new SparqlUpdateException("Cannot call ExecuteUpdate() when the UpdateProcessor property has not been set");
            }

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(this.ToString());

            this._updateProcessor.ProcessCommandSet(cmds);
        }
        public void Commit(SparqlParameterizedString updateTasks)
        {
            if (updateTasks != null)
            {
                var processor    = new LeviathanUpdateProcessor(_dataset);
                var sparqlParser = new SparqlUpdateParser();

                AddAllColidNamespaces(updateTasks);

                var query = sparqlParser.ParseFromString(updateTasks);
                processor.ProcessCommandSet(query);
            }
        }
示例#20
0
 public void Infer(EntailmentRegime entailmentRegime = EntailmentRegime.RDFS)
 {
     foreach (var rule in GetRulesForRegime(entailmentRegime, GetType().Assembly))
     {
         if (!string.IsNullOrWhiteSpace(rule))
         {
             var sps    = new SparqlParameterizedString(rule);
             var parser = new SparqlUpdateParser();
             var query  = parser.ParseFromString(sps);
             query.Process(_updateProcessor);
         }
     }
 }
        public void SparqlUpdateDeleteCommandWithNoMatchingGraph()
        {
            var dataset = new InMemoryDataset();
            var egGraph = new Uri("http://example.org/graph");

            dataset.HasGraph(egGraph).Should().BeFalse();
            var processor = new LeviathanUpdateProcessor(dataset);
            var cmdSet    = new SparqlUpdateParser().ParseFromString(
                "WITH <" + egGraph + "> DELETE {} WHERE {}");

            processor.ProcessCommandSet(cmdSet);
            dataset.HasGraph(egGraph).Should().BeFalse();
        }
示例#22
0
        /// <summary>
        /// Processes a PATCH operation.
        /// </summary>
        /// <param name="context">HTTP Context.</param>
        public override void ProcessPatch(IHttpContext context)
        {
            // Work out the Graph URI we want to patch
            Uri graphUri = ResolveGraphUri(context);

            // If the Request has the SPARQL Update MIME Type then we can process it
            if (context.Request.ContentLength > 0)
            {
                if (context.Request.ContentType.Equals("application/sparql-update"))
                {
                    // Try and parse the SPARQL Update
                    // No error handling here as we assume the calling IHttpHandler does that
                    String patchData;
                    using (StreamReader reader = new StreamReader(context.Request.InputStream))
                    {
                        patchData = reader.ReadToEnd();
                        reader.Close();
                    }
                    SparqlUpdateParser     parser = new SparqlUpdateParser();
                    SparqlUpdateCommandSet cmds   = parser.ParseFromString(patchData);

                    // Assuming that we've got here i.e. the SPARQL Updates are parseable then
                    // we need to check that they actually affect the relevant Graph
                    if (cmds.Commands.All(c => c.AffectsSingleGraph && c.AffectsGraph(graphUri)))
                    {
                        GenericUpdateProcessor processor = new GenericUpdateProcessor(_manager);
                        processor.ProcessCommandSet(cmds);
                        processor.Flush();
                    }
                    else
                    {
                        // One/More commands either do no affect a Single Graph or don't affect the Graph
                        // implied by the HTTP Request so give a 422 response
                        context.Response.StatusCode = 422;
                        return;
                    }
                }
                else
                {
                    // Don't understand other forms of PATCH requests
                    context.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType;
                    return;
                }
            }
            else
            {
                // Empty Request is a Bad Request
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }
        }
示例#23
0
        public void SparqlParameterizedString()
        {
            String test = @"INSERT DATA { GRAPH @graph {
                            <http://uri> <http://uri> <http://uri>
                            }}";
            SparqlParameterizedString cmdString = new SparqlParameterizedString(test);

            cmdString.SetUri("graph", new Uri("http://example.org/graph"));

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(cmdString);

            cmds.ToString();
        }
示例#24
0
        /// <summary>
        /// Applies SPARQL Updates to the Store.
        /// </summary>
        /// <param name="sparqlUpdate">SPARQL Update.</param>
        public void Update(String sparqlUpdate)
        {
            if (_updateParser == null)
            {
                _updateParser = new SparqlUpdateParser();
            }
            SparqlUpdateCommandSet cmds = _updateParser.ParseFromString(sparqlUpdate);

            if (_updateProcessor == null)
            {
                _updateProcessor = new LeviathanUpdateProcessor(_dataset);
            }
            _updateProcessor.ProcessCommandSet(cmds);
        }
示例#25
0
        public void SparqlUpdateInsertCommand2()
        {
            SparqlParameterizedString command = new SparqlParameterizedString();

            command.Namespaces.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));
            command.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS));
            command.CommandText  = "INSERT { ?s rdf:type ?class } USING <http://example.org/temp> WHERE { ?s a ?type . ?type rdfs:subClassOf+ ?class };";
            command.CommandText += "INSERT { ?s ?property ?value } USING <http://example.org/temp> WHERE {?s ?p ?value . ?p rdfs:subPropertyOf+ ?property };";
            command.CommandText += "INSERT { ?s rdf:type rdfs:Class } USING <http://example.org/temp> WHERE { ?s rdfs:subClassOf ?class };";
            command.CommandText += "INSERT { ?s rdf:type rdf:Property } USING <http://example.org/temp> WHERE { ?s rdfs:subPropertyOf ?property };";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            g.BaseUri = new Uri("http://example.org/temp");
            store.Add(g);
            int origTriples = g.Triples.Count;

            SparqlUpdateParser       parser    = new SparqlUpdateParser();
            SparqlUpdateCommandSet   cmds      = parser.ParseFromString(command);
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);

            processor.ProcessCommandSet(cmds);

            Assert.AreEqual(origTriples, g.Triples.Count, "Triples in input Graph shouldn't have changed as INSERTs should have gone to the default graph");

            IGraph def = store[null];

            TestTools.ShowGraph(def);
            Console.WriteLine();

            //Apply a RDFS reasoner over the original input and output it into another graph
            //Should be equivalent to the default Graph
            Graph        h        = new Graph();
            RdfsReasoner reasoner = new RdfsReasoner();

            reasoner.Apply(g, h);

            TestTools.ShowGraph(h);

            GraphDiffReport report = h.Difference(def);

            if (!report.AreEqual)
            {
                TestTools.ShowDifferences(report);

                Assert.IsTrue(report.RemovedTriples.Count() == 1, "Should have only 1 missing Triple (due to rdfs:domain inference which is hard to encode in an INSERT command)");
            }
        }
        private void SparqlMathTest()
        {
            const string update = @"
DELETE { ?s ?p ?o. }
INSERT { ?s ?p ?a. }
WHERE  { ?s ?p ?o. BIND(?o / 2 AS ?a) }
";
            const string query  = @"SELECT * WHERE { ?s ?p ?o.}";

            var graph = new Graph();

            graph.Assert(graph.CreateBlankNode(), graph.CreateBlankNode(), 0.5.ToLiteral(graph));
            Assert.Equal(0.5, graph.Triples.Select(t => t.Object.AsValuedNode().AsDouble()).First());

            var store = new TripleStore();

            store.Add(graph);

            var queryProcessor = new LeviathanQueryProcessor(store);
            var queryParser    = new SparqlQueryParser();
            var q      = queryParser.ParseFromString(query);
            var result = q.Process(queryProcessor) as SparqlResultSet;
            var oNode  = result.First()["o"];

            Assert.Equal("0.5", ((ILiteralNode)oNode).Value);

            q = queryParser.ParseFromString("SELECT ?a WHERE { ?s ?p ?o. BIND(?o / 2 AS ?a) }");
            //q = queryParser.ParseFromString("SELECT ?a WHERE { BIND (0.25 as ?a) }");
            result = q.Process(queryProcessor) as SparqlResultSet;
            oNode  = result.First()["a"];
            var o = oNode.AsValuedNode().AsDouble();

            Assert.Equal(0.25, o);
            Assert.Equal("0.25", ((ILiteralNode)oNode).Value);


            var updateProcessor = new LeviathanUpdateProcessor(store);
            var updateParser    = new SparqlUpdateParser();

            updateParser.ParseFromString(update).Process(updateProcessor);

            result = queryParser.ParseFromString(query).Process(queryProcessor) as SparqlResultSet;
            oNode  = result.First()["o"];
            //Assert.Equal("0.25", ((ILiteralNode)oNode).Value);
            o = oNode.AsValuedNode().AsDouble();
            Assert.Equal(0.25, o);
            //@object is 25 when using German (Germany) regional format
            //@object is 0.25 when using English (United Kingdom) regional format
        }
示例#27
0
        private void TestDropGraphCommit()
        {
            ISparqlDataset dataset = this.GetNonEmptyDataset();

            String updates = "DROP GRAPH <" + TestGraphUri.ToString() + ">";

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(updates);

            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            processor.ProcessCommandSet(cmds);

            Assert.False(dataset.HasGraph(TestGraphUri), "Graph should not exist");
        }
        public void ApplyTransaction(IList <Triple> preconditions, IList <Triple> deletePatterns, IList <Triple> inserts,
                                     string updateGraphUri)
        {
            if (preconditions.Count > 0)
            {
                throw new NotSupportedException("SparqlDataObjectStore does not support conditional updates");
            }

            var deleteOp = FormatDeletePatterns(deletePatterns, updateGraphUri);
            var insertOp = FormatInserts(inserts, updateGraphUri);

            var parser = new SparqlUpdateParser();
            var cmds   = parser.ParseFromString(deleteOp + "\n" + insertOp);

            _updateProcessor.ProcessCommandSet(cmds);
        }
示例#29
0
        public void SparqlUpdateChangesNotReflectedInOriginalGraph1()
        {
            //Test Case originally submitted by Tomasz Pluskiewicz

            // given
            IGraph sourceGraph = new Graph();

            sourceGraph.LoadFromString(@"@prefix ex: <http://www.example.com/> .
ex:Subject ex:hasObject ex:Object .");

            IGraph expectedGraph = new Graph();

            expectedGraph.LoadFromString(@"@prefix ex: <http://www.example.com/> .
ex:Subject ex:hasBlank [ ex:hasObject ex:Object ] .");


            //IMPORTANT - Because we create the dataset without an existing store it
            //creates a new triple store internally which has a single unnamed graph
            //Then when we add another unnamed graph it merges into that existing graph,
            //this is why the update does not apply to the added graph but rather to
            //the merged graph that is internal to the dataset
            ISparqlDataset dataset = new InMemoryDataset(true);

            dataset.AddGraph(sourceGraph);

            // when
            var command = new SparqlParameterizedString
            {
                CommandText = @"PREFIX ex: <http://www.example.com/>
DELETE { ex:Subject ex:hasObject ex:Object . }
INSERT { ex:Subject ex:hasBlank [ ex:hasObject ex:Object ] . }
WHERE { ?s ?p ?o . }"
            };
            SparqlUpdateCommandSet   cmds      = new SparqlUpdateParser().ParseFromString(command);
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);

            processor.ProcessCommandSet(cmds);

            Assert.Single(dataset.Graphs);

            IGraph g = dataset.Graphs.First();

            Assert.Equal(2, g.Triples.Count);
            Assert.False(ReferenceEquals(g, sourceGraph), "Result Graph should not be the Source Graph");
            Assert.Equal(1, sourceGraph.Triples.Count);
            Assert.NotEqual(expectedGraph, sourceGraph);
        }
示例#30
0
        public void SparqlUpdateInsertCommand()
        {
            SparqlParameterizedString command = new SparqlParameterizedString();

            command.Namespaces.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));
            command.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS));
            command.CommandText  = "INSERT { ?s rdf:type ?class } WHERE { ?s a ?type . ?type rdfs:subClassOf+ ?class };";
            command.CommandText += "INSERT { ?s ?property ?value } WHERE {?s ?p ?value . ?p rdfs:subPropertyOf+ ?property };";
            command.CommandText += "INSERT { ?s rdf:type rdfs:Class } WHERE { ?s rdfs:subClassOf ?class };";
            command.CommandText += "INSERT { ?s rdf:type rdf:Property } WHERE { ?s rdfs:subPropertyOf ?property };";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            g.Retract(g.Triples.Where(t => !t.IsGroundTriple).ToList());
            g.BaseUri = null;
            store.Add(g);

            SparqlUpdateParser       parser    = new SparqlUpdateParser();
            SparqlUpdateCommandSet   cmds      = parser.ParseFromString(command);
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);

            processor.ProcessCommandSet(cmds);

            TestTools.ShowGraph(g);
            Console.WriteLine();

            //Now reload the test data and apply an RDFS reasoner over it
            //This should give us a Graph equivalent to the one created by the previous INSERT commands
            Graph h = new Graph();

            FileLoader.Load(h, "InferenceTest.ttl");
            h.Retract(h.Triples.Where(t => !t.IsGroundTriple).ToList());
            RdfsReasoner reasoner = new RdfsReasoner();

            reasoner.Apply(h);

            GraphDiffReport diff = h.Difference(g);

            if (!diff.AreEqual)
            {
                TestTools.ShowDifferences(diff);
            }

            Assert.AreEqual(h, g, "Graphs should be equal");
        }