static object Execute(TripleStore store, string sparql) { InMemoryDataset ds = new InMemoryDataset(store); ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds); SparqlQueryParser sparqlparser = new SparqlQueryParser(); SparqlQuery query = sparqlparser.ParseFromString(sparql); return processor.ProcessQuery(query); }
private ISparqlDataset GetTestData() { InMemoryDataset dataset = new InMemoryDataset(); Graph g = new Graph(); FileLoader.Load(g, "InferenceTest.ttl"); dataset.AddGraph(g); return dataset; }
public void Setup() { this._parser = new SparqlQueryParser(); TripleStore store = new TripleStore(); Graph g = new Graph(); FileLoader.Load(g, "describe-algos.ttl"); store.Add(g); this._data = new InMemoryDataset(store); }
protected virtual ISparqlDataset GetNonEmptyDataset() { InMemoryDataset dataset = new InMemoryDataset(); Graph g = new Graph(); g.BaseUri = TestGraphUri; dataset.AddGraph(g); return dataset; }
/// <summary> /// Tries to load a SPARQL Dataset based on information from the Configuration Graph /// </summary> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> /// <param name="targetType">Target Type</param> /// <param name="obj">Output Object</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; switch (targetType.FullName) { case InMemoryDataset: INode storeNode = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingStore)); if (storeNode == null) { throw new DotNetRdfConfigurationException("Unable to load the In-Memory Dataset identified by the Node '" + objNode.ToString() + "' since there was no value given for the required property dnr:usingStore"); } else { Object temp = ConfigurationLoader.LoadObject(g, storeNode); if (temp is IInMemoryQueryableStore) { obj = new InMemoryDataset((IInMemoryQueryableStore)temp); return true; } else { throw new DotNetRdfConfigurationException("Unable to load the In-Memory Dataset identified by the Node '" + objNode.ToString() + "' since the Object pointed to by the dnr:usingStore property could not be loaded as an object which implements the IInMemoryQueryableStore interface"); } } #if !NO_DATA && !NO_STORAGE case SqlDataset: INode sqlManager = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertySqlManager)); if (sqlManager == null) { throw new DotNetRdfConfigurationException("Unable to load the SQL Dataset identified by the Node '" + objNode.ToString() + "' since there was no value given for the required property dnr:sqlManager"); } else { Object temp = ConfigurationLoader.LoadObject(g, sqlManager); if (temp is IDotNetRDFStoreManager) { obj = new SqlDataset((IDotNetRDFStoreManager)temp); return true; } else { throw new DotNetRdfConfigurationException("Unable to load the SQL Dataset identified by the Node '" + objNode.ToString() + "' since the Object pointed to by the dnr:sqlManager property could not be laoded as an object which implements the IDotNetRDFStoreManager interface"); } } #endif } return false; }
public void SparqlDatasetDefaultGraphManagementWithUpdate5() { TripleStore store = new TripleStore(); Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/graph"); store.Add(g); Graph h = new Graph(); h.BaseUri = new Uri("http://example.org/someOtherGraph"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store, h.BaseUri); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString("LOAD <http://www.dotnetrdf.org/configuration#>; WITH <http://example.org/graph> INSERT { ?s a ?type } USING <http://example.org/someOtherGraph> WHERE { ?s a ?type }; DELETE WHERE { ?s a ?type }"); processor.ProcessCommandSet(cmds); Assert.IsFalse(g.IsEmpty, "First Graph should not be empty as should have been filled by the INSERT command"); Assert.IsFalse(h.IsEmpty, "Second Graph should not be empty as should not have been filled by the LOAD command"); Assert.IsFalse(h.HasSubGraph(g), "First Graph should not be a subgraph of the Second Graph as the DELETE should have eliminated the subgraph relationship"); }
public void SparqlDatasetDefaultGraphManagementWithUpdate3() { TripleStore store = new TripleStore(); Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/graph"); store.Add(g); Graph h = new Graph(); h.BaseUri = new Uri("http://example.org/someOtherGraph"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store, h.BaseUri); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString("LOAD <http://www.dotnetrdf.org/configuration#> INTO GRAPH <http://example.org/graph>; LOAD <http://www.dotnetrdf.org/configuration#> INTO GRAPH <http://example.org/someOtherGraph>"); processor.ProcessCommandSet(cmds); Assert.IsFalse(g.IsEmpty, "First Graph should not be empty as should have been filled by the first LOAD command"); Assert.IsFalse(h.IsEmpty, "Second Graph should not be empty as should not have been filled by the second LOAD command"); Assert.AreEqual(g, h, "Graphs should be equal"); }
public void SparqlDatasetDefaultGraphManagementWithUpdate() { TripleStore store = new TripleStore(); Graph g = new Graph(); store.Add(g); Graph h = new Graph(); h.BaseUri = new Uri("http://example.org/someOtherGraph"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store, h.BaseUri); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString("LOAD <http://www.dotnetrdf.org/configuration#>"); processor.ProcessCommandSet(cmds); Assert.IsTrue(g.IsEmpty, "Graph with null URI (normally the default Graph) should be empty as the Default Graph for the Dataset should have been a named Graph so this Graph should not have been filled by the LOAD Command"); Assert.IsFalse(h.IsEmpty, "Graph with name should be non-empty as it should have been the Default Graph for the Dataset and so filled by the LOAD Command"); }
public void SparqlDatasetDefaultGraphManagement2() { TripleStore store = new TripleStore(); Graph g = new Graph(); g.Assert(g.CreateUriNode(new Uri("http://example.org/subject")), g.CreateUriNode(new Uri("http://example.org/predicate")), g.CreateUriNode(new Uri("http://example.org/object"))); store.Add(g); Graph h = new Graph(); h.BaseUri = new Uri("http://example.org/someOtherGraph"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store); dataset.SetDefaultGraph(g); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString("SELECT * WHERE { ?s ?p ?o }"); Object results = processor.ProcessQuery(q); if (results is SparqlResultSet) { TestTools.ShowResults(results); Assert.IsFalse(((SparqlResultSet)results).IsEmpty, "Results should be false as a non-empty Graph was set as the Default Graph"); } else { Assert.Fail("ASK Query did not return a SPARQL Result Set as expected"); } }
public void SparqlPropertyPathEvaluationZeroOrMorePathReverse() { TripleStore store = new TripleStore(); Graph g = new Graph(); g.LoadFromFile("InferenceTest.ttl"); store.Add(g); InMemoryDataset dataset = new InMemoryDataset(store); ZeroOrMore path = new ZeroOrMore(new Property(this._factory.CreateUriNode(new Uri(NamespaceMapper.RDFS + "subClassOf")))); INode airVehicle = this._factory.CreateUriNode(new Uri("http://example.org/vehicles/AirVehicle")); ISparqlAlgebra algebra = this.GetAlgebra(path, null, airVehicle); BaseMultiset results = algebra.Evaluate(new SparqlEvaluationContext(null, dataset)); TestTools.ShowMultiset(results); Assert.IsFalse(results.IsEmpty, "Results should not be empty"); }
private int ProcessEvaluationTest(SparqlQueryParser parser, Triple commentDef, String queryFile, String dataFile, List<String> dataFiles, String resultFile) { Console.WriteLine("# Processing Evaluation Test " + Path.GetFileName(queryFile)); if (commentDef != null) { Console.WriteLine(commentDef.Object.ToString()); Console.WriteLine(); } if (dataFiles.Contains(dataFile)) dataFiles.Remove(dataFile); if (queryFile.StartsWith("file:///")) queryFile = queryFile.Substring(8); if (dataFile != null && dataFile.StartsWith("file:///")) dataFile = dataFile.Substring(8); if (resultFile.StartsWith("file:///")) resultFile = resultFile.Substring(8); Console.WriteLine("Query File is " + queryFile); if (evaluationTestOverride.Any(x => queryFile.EndsWith(x))) { Console.WriteLine(); Console.WriteLine("# Test Result = Manually overridden to Pass (Test Passed)"); testsPassed++; testsEvaluationPassed++; return 1; } if (dataFile != null) Console.WriteLine("Default Graph File is " + dataFile); foreach (String file in dataFiles) { Console.WriteLine("Uses Named Graph File " + file); } Console.WriteLine("Expected Result File is " + resultFile); Console.WriteLine(); SparqlQuery query; try { query = parser.ParseFromFile(queryFile); Console.WriteLine(query.ToString()); Console.WriteLine(); Console.WriteLine("Formatted with SparqlFormatter"); SparqlFormatter formatter = new SparqlFormatter(query.NamespaceMap); Console.WriteLine(formatter.Format(query)); Console.WriteLine(); try { Console.WriteLine(query.ToAlgebra().ToString()); Console.WriteLine(); } catch { //Do Nothing } } catch (RdfParseException parseEx) { this.ReportError("Query Parser Error", parseEx); testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result = Unable to parse query (Test Failed)"); return -1; } IInMemoryQueryableStore store; if (dataFile != null) { store = new TripleStore(); } else { store = new WebDemandTripleStore(); } //Load Default Graph Graph defaultGraph = new Graph(); try { if (dataFile != null) { FileLoader.Load(defaultGraph, dataFile); } store.Add(defaultGraph); } catch (RdfParseException parseEx) { this.ReportError("Parser Error", parseEx); testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result = Unable to parse Default Graph (Test Failed)"); return -1; } //Load Named Graphs try { foreach (String graphFile in dataFiles) { Graph namedGraph = new Graph(); if (graphFile.StartsWith("file:///")) { FileLoader.Load(namedGraph, graphFile.Substring(8)); } else { FileLoader.Load(namedGraph, graphFile); } store.Add(namedGraph); } } catch (RdfParseException parseEx) { this.ReportError("Parser Error", parseEx); testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result - Unable to parse Named Graph (Test Failed)"); return -1; } //Create a Dataset and then Set Graphs InMemoryDataset dataset = new InMemoryDataset(store); if (!query.DefaultGraphs.Any()) { query.AddDefaultGraph(defaultGraph.BaseUri); //dataset.SetActiveGraph(defaultGraph.BaseUri); } if (!query.NamedGraphs.Any()) { foreach (String namedGraphUri in dataFiles) { query.AddNamedGraph(new Uri(namedGraphUri)); } } //Try and get the result Object results = null; try { results = query.Evaluate(dataset); } catch (RdfQueryException queryEx) { this.ReportError("Query Error", queryEx); testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result - Query execution failed (Test Failed)"); return -1; } catch (Exception ex) { this.ReportError("Other Error", ex); testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result - Query failed (Test Failed)"); return -1; } if (results == null) { testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result - No result was returned from the Query (Test Failed)"); return -1; } //Load in the expected results if (results is SparqlResultSet) { //Save our Results so we can manually compare as needed SparqlResultSet ourResults = (SparqlResultSet)results; SparqlXmlWriter writer = new SparqlXmlWriter(); writer.Save(ourResults, resultFile + ".out"); SparqlResultSet expectedResults = new SparqlResultSet(); if (resultFile.EndsWith(".srx")) { try { SparqlXmlParser resultSetParser = new SparqlXmlParser(); resultSetParser.Load(expectedResults, resultFile); } catch (RdfParseException parseEx) { this.ReportError("Result Set Parser Error", parseEx); testsIndeterminate++; testsEvaluationIndeterminate++; Console.WriteLine("# Test Result - Error loading expected Result Set (Test Indeterminate)"); return 0; } } else if (resultFile.EndsWith(".ttl") || resultFile.EndsWith(".rdf")) { try { SparqlRdfParser resultSetParser = new SparqlRdfParser(); resultSetParser.Load(expectedResults, resultFile); } catch (RdfParseException parseEx) { this.ReportError("Result Set Parser Error", parseEx); testsIndeterminate++; testsEvaluationIndeterminate++; Console.WriteLine("# Test Result - Error loading expected Result Set (Test Indeterminate)"); return 0; } } else { testsIndeterminate++; testsEvaluationIndeterminate++; Console.WriteLine("# Test Result - Unable to load the expected Result Set (Test Indeterminate)"); return 0; } try { ourResults.Trim(); expectedResults.Trim(); if (ourResults.Equals(expectedResults)) { testsPassed++; testsEvaluationPassed++; Console.WriteLine("# Test Result - Result Set as expected (Test Passed)"); return 1; } else { Console.WriteLine("Final Query"); Console.WriteLine(query.ToString()); Console.WriteLine(); this.ShowTestData(store); this.ShowResultSets(ourResults, expectedResults); testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result - Result Set not as expected (Test Failed)"); return -1; } } catch (NotImplementedException) { this.ShowResultSets(ourResults, expectedResults); testsIndeterminate++; testsEvaluationIndeterminate++; Console.WriteLine("# Test Result - Unable to establish if Result Set was as expected (Test Indeterminate)"); return 0; } } else if (results is Graph) { if (resultFile.EndsWith(".ttl")) { //Save our Results so we can manually compare as needed Graph ourResults = (Graph)results; CompressingTurtleWriter writer = new CompressingTurtleWriter(); writer.Save(ourResults, resultFile + ".out"); try { Graph expectedResults = new Graph(); TurtleParser ttlparser = new TurtleParser(); ttlparser.Load(expectedResults, resultFile); try { if (ourResults.Equals(expectedResults)) { testsPassed++; testsEvaluationPassed++; Console.WriteLine("# Test Result - Graph as expected (Test Passed)"); return 1; } else { this.ShowTestData(store); this.ShowGraphs(ourResults, expectedResults); testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result - Graph not as expected (Test Failed)"); return -1; } } catch (NotImplementedException) { this.ShowGraphs(ourResults, expectedResults); testsIndeterminate++; testsEvaluationIndeterminate++; Console.WriteLine("# Test Result - Unable to establish if Graph was as expected (Test Indeterminate)"); return 0; } } catch (RdfParseException parseEx) { this.ReportError("Graph Parser Error", parseEx); testsIndeterminate++; testsEvaluationIndeterminate++; Console.WriteLine("# Test Result - Error loading expected Graph (Test Indeterminate)"); return 0; } } else { testsIndeterminate++; testsEvaluationIndeterminate++; Console.WriteLine("# Test Result - Unable to load expected Graph (Test Indeterminate)"); return 0; } } else { testsFailed++; testsEvaluationFailed++; Console.WriteLine("# Test Result - Didn't produce a Graph as expected (Test Failed)"); return -1; } }
public void SparqlEvaluationComplexOptionalGraphUnion() { SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromFile("q-opt-complex-4.rq"); TripleStore store = new TripleStore(); Graph g = new Graph(); FileLoader.Load(g, "complex-data-2.ttl"); store.Add(g); Graph h = new Graph(); FileLoader.Load(h, "complex-data-1.ttl"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store); q.AddDefaultGraph(g.BaseUri); q.AddNamedGraph(h.BaseUri); SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap); Object results; //Examine limited parts of the Query to see why it doesn't work properly SparqlParameterizedString unionClause = new SparqlParameterizedString(); unionClause.Namespaces = q.NamespaceMap; unionClause.QueryText = "SELECT * WHERE { ?person foaf:name ?name . { ?person ex:healthplan ?plan . } UNION { ?person ex:department ?dept . } }"; SparqlQuery unionQuery = parser.ParseFromString(unionClause); Console.WriteLine("UNION Clause Only"); Console.WriteLine(formatter.Format(unionQuery)); results = unionQuery.Evaluate(dataset); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); } else { Assert.Fail("Didn't get a Result Set as expected"); } Console.WriteLine(); //Try the Optional Clause SparqlParameterizedString optionalClause = new SparqlParameterizedString(); optionalClause.Namespaces = q.NamespaceMap; optionalClause.QueryText = "SELECT * WHERE { OPTIONAL { ?person a foaf:Person . GRAPH ?g { [] foaf:depiction ?img ; foaf:name ?name } } }"; SparqlQuery optionalQuery = parser.ParseFromString(optionalClause); Console.WriteLine("OPTIONAL Clause Only"); Console.WriteLine(formatter.Format(optionalQuery)); results = optionalQuery.Evaluate(dataset); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); } else { Assert.Fail("Didn't get a Result Set as expected"); } Console.WriteLine(); //Try the full Query with a SELECT * to examine all the values SparqlParameterizedString fullQuery = new SparqlParameterizedString(); fullQuery.Namespaces = q.NamespaceMap; fullQuery.QueryText = "SELECT * WHERE { ?person foaf:name ?name . { ?person ex:healthplan ?plan . } UNION { ?person ex:department ?dept . } OPTIONAL { ?person a foaf:Person . GRAPH ?g { [] foaf:depiction ?img ; foaf:name ?name } } }"; SparqlQuery q2 = parser.ParseFromString(fullQuery); Console.WriteLine("Full Query as a SELECT *"); Console.WriteLine(formatter.Format(q2)); results = q2.Evaluate(dataset); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); } else { Assert.Fail("Didn't get a Result Set as expected"); } Console.WriteLine(); //Try the full Query Console.WriteLine("Full Query"); Console.WriteLine(formatter.Format(q)); results = q.Evaluate(dataset); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); SparqlRdfParser resultsParser = new SparqlRdfParser(new TurtleParser()); SparqlResultSet expected = new SparqlResultSet(); resultsParser.Load(expected, "result-opt-complex-4.ttl"); Console.WriteLine(); Console.WriteLine("Expected Results"); TestTools.ShowResults(expected); Assert.AreEqual(rset, expected, "Result Sets should be equal"); } else { Assert.Fail("Didn't get a Result Set as expected"); } }
public void SparqlUpdateDeleteDataCombination() { SparqlParameterizedString command = new SparqlParameterizedString(); command.Namespaces.AddNamespace("ex", new Uri("http://example.org/")); command.CommandText = "DELETE 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(); IGraph def = new Graph(); def.NamespaceMap.Import(command.Namespaces); def.Assert(new Triple(def.CreateUriNode("ex:a"), def.CreateUriNode("ex:b"), def.CreateUriNode("ex:c"))); dataset.AddGraph(def); IGraph ex = new Graph(); ex.BaseUri = new Uri("http://example.org/graph"); ex.NamespaceMap.Import(command.Namespaces); ex.Assert(new Triple(ex.CreateUriNode("ex:a"), ex.CreateUriNode("ex:b"), ex.CreateUriNode("ex:c"))); dataset.AddGraph(ex); 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")); def = dataset[null]; Assert.AreEqual(0, def.Triples.Count, "Should be 0 Triples in the Default Graph"); Assert.IsFalse(def.ContainsTriple(t), "Should not have the deleted Triple in the Default Graph"); ex = dataset[new Uri("http://example.org/graph")]; Assert.AreEqual(0, ex.Triples.Count, "Should be 0 Triples in the Named Graph"); Assert.IsFalse(ex.ContainsTriple(t), "Should not have the deleted Triple in the Named Graph"); }
private void SparqlQueryAndUpdateThreadSafeEvaluationActual() { String query1 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/1> { ?s ?p ?o } }"; String query2 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/2> { ?s ?p ?o } }"; String query3 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/3> { ?s ?p ?o } }"; String update1 = "INSERT DATA { GRAPH <http://example.org/3> { <ex:subj> <ex:pred> <ex:obj> } }"; SparqlQuery q1 = this._parser.ParseFromString(query1); SparqlQuery q2 = this._parser.ParseFromString(query2); SparqlQuery q3 = this._parser.ParseFromString(query3); Assert.IsFalse(q1.UsesDefaultDataset, "Query 1 should not be thread safe"); Assert.IsFalse(q2.UsesDefaultDataset, "Query 2 should not be thread safe"); Assert.IsFalse(q3.UsesDefaultDataset, "Query 3 should not be thread safe"); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(update1); InMemoryDataset dataset = new InMemoryDataset(); Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); g.BaseUri = new Uri("http://example.org/1"); Graph h = new Graph(); h.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.Functions.LeviathanFunctionLibrary.ttl"); h.BaseUri = new Uri("http://example.org/2"); Graph i = new Graph(); i.BaseUri = new Uri("http://example.org/3"); dataset.AddGraph(g); dataset.AddGraph(h); dataset.AddGraph(i); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); LeviathanUpdateProcessor upProcessor = new LeviathanUpdateProcessor(dataset); QueryWithGraphDelegate d = new QueryWithGraphDelegate(this.QueryWithGraph); RunUpdateDelegate d2 = new RunUpdateDelegate(this.RunUpdate); IAsyncResult r1 = d.BeginInvoke(q1, processor, null, null); IAsyncResult r2 = d.BeginInvoke(q2, processor, null, null); IAsyncResult r3 = d.BeginInvoke(q3, processor, null, null); IAsyncResult r4 = d2.BeginInvoke(cmds, upProcessor, null, null); WaitHandle.WaitAll(new WaitHandle[] { r1.AsyncWaitHandle, r2.AsyncWaitHandle, r3.AsyncWaitHandle, r4.AsyncWaitHandle }); IGraph gQuery = d.EndInvoke(r1); Assert.AreEqual(g, gQuery, "Query 1 Result not as expected"); IGraph hQuery = d.EndInvoke(r2); Assert.AreEqual(h, hQuery, "Query 2 Result not as expected"); IGraph iQuery = d.EndInvoke(r3); if (iQuery.IsEmpty) { Console.WriteLine("Query 3 executed before the INSERT DATA command - running again to get the resulting graph"); iQuery = this.QueryWithGraph(q3, processor); } else { Console.WriteLine("Query 3 executed after the INSERT DATA command"); } //Test iQuery against an empty Graph Assert.IsFalse(iQuery.IsEmpty, "Graph should not be empty as INSERT DATA should have inserted a Triple"); Assert.AreNotEqual(new Graph(), iQuery, "Graphs should not be equal"); Assert.AreNotEqual(g, h, "Graphs should not be different"); }
public void SparqlUpdateInsertCommand4() { 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 { GRAPH ?g { ?s a ?type . ?type rdfs:subClassOf+ ?class } };"; command.CommandText += "INSERT { ?s ?property ?value } USING NAMED <http://example.org/temp> WHERE { GRAPH ?g { ?s ?p ?value . ?p rdfs:subPropertyOf+ ?property } };"; command.CommandText += "INSERT { ?s rdf:type rdfs:Class } USING NAMED <http://example.org/temp> WHERE { GRAPH ?g { ?s rdfs:subClassOf ?class } };"; command.CommandText += "INSERT { ?s rdf:type rdf:Property } USING NAMED <http://example.org/temp> WHERE { GRAPH ?g { ?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(store.Graph(null)); processor.ProcessCommandSet(cmds); IGraph def = store.Graph(null); TestTools.ShowGraph(def); //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)"); } }
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(store.Graph(null)); processor.ProcessCommandSet(cmds); IGraph def = store.Graph(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"); }
private int ProcessUpdateEvaluationTest(IGraph manifest, INode testNode) { try { IUriNode utData = manifest.CreateUriNode("ut:data"); IUriNode utGraph = manifest.CreateUriNode("ut:graph"); IUriNode utGraphData = manifest.CreateUriNode("ut:graphData"); IUriNode rdfsLabel = manifest.CreateUriNode("rdfs:label"); //Get the test name and comment String name = manifest.GetTriplesWithSubjectPredicate(testNode, manifest.CreateUriNode("mf:name")).Select(t => t.Object).First().ToString(); String comment = manifest.GetTriplesWithSubjectPredicate(testNode, manifest.CreateUriNode("rdfs:comment")).Select(t => t.Object).First().ToString(); //Get the test action and file INode actionNode = manifest.GetTriplesWithSubjectPredicate(testNode, manifest.CreateUriNode("mf:action")).Select(t => t.Object).First(); String updateFile = manifest.GetTriplesWithSubjectPredicate(actionNode, manifest.CreateUriNode("ut:request")).Select(t => t.Object).First().ToString(); Console.WriteLine("# Processing Update Evaluation Test " + updateFile); Console.WriteLine(name); Console.WriteLine(comment); Console.WriteLine(); if (evaluationTestOverride.Any(x => updateFile.EndsWith(x))) { Console.WriteLine(); Console.WriteLine("# Test Result = Manually overridden to Pass (Test Passed)"); testsPassed++; testsEvaluationPassed++; return 1; } //Parse the Update SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds; try { if (updateFile.StartsWith("file:///")) { updateFile = updateFile.Substring(8); } cmds = parser.ParseFromFile(updateFile); Console.WriteLine("Update Commands:"); Console.WriteLine(cmds.ToString()); } catch (Exception ex) { this.ReportError("Error Parsing Update Commands", ex); Console.WriteLine("# Test Result - Update Command failed to pass (Test Failed)"); testsEvaluationFailed++; testsFailed++; return -1; } //Build the Initial Dataset InMemoryDataset dataset = new InMemoryDataset(new TripleStore()); try { foreach (Triple t in manifest.GetTriplesWithSubjectPredicate(actionNode, utData)) { Console.WriteLine("Uses Default Graph File " + t.Object.ToString()); Graph g = new Graph(); UriLoader.Load(g, ((IUriNode)t.Object).Uri); g.BaseUri = null; dataset.AddGraph(g); } foreach (Triple t in manifest.GetTriplesWithSubjectPredicate(actionNode, utGraphData)) { Graph g = new Graph(); INode dataNode = manifest.GetTriplesWithSubjectPredicate(t.Object, utData).Concat(manifest.GetTriplesWithSubjectPredicate(t.Object, utGraph)).Select(x => x.Object).FirstOrDefault(); UriLoader.Load(g, ((IUriNode)dataNode).Uri); INode nameNode = manifest.GetTriplesWithSubjectPredicate(t.Object, rdfsLabel).Select(x => x.Object).FirstOrDefault(); g.BaseUri = new Uri(nameNode.ToString()); Console.WriteLine("Uses Named Graph File " + dataNode.ToString() + " named as " + nameNode.ToString()); dataset.AddGraph(g); } } catch (Exception ex) { this.ReportError("Error Building Initial Dataset", ex); Console.WriteLine("# Test Result - Unable to build Initial Dataset (Test Indeterminate)"); testsEvaluationIndeterminate++; testsIndeterminate++; return 0; } Console.WriteLine(); //Try running the Update try { LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); //Since all Tests assume that the WHERE is limited to the unnamed default graph unless specified //then must set this to be the Active Graph for the dataset dataset.SetDefaultGraph(dataset[null]); //Try the Update processor.ProcessCommandSet(cmds); dataset.ResetDefaultGraph(); } catch (SparqlUpdateException updateEx) { //TODO: Some Update tests might be to test cases where a failure should occur this.ReportError("Unexpected Error while performing Update", updateEx); Console.WriteLine("# Test Result - Update Failed (Test Failed)"); testsEvaluationFailed++; testsFailed++; return -1; } catch (Exception ex) { this.ReportError("Unexpected Error while performing Update", ex); Console.WriteLine("# Test Result - Update Failed (Test Failed)"); testsEvaluationFailed++; testsFailed++; return -1; } //Build the Result Dataset INode resultNode = manifest.GetTriplesWithSubjectPredicate(testNode, manifest.CreateUriNode("mf:result")).Select(t => t.Object).First(); InMemoryDataset resultDataset = new InMemoryDataset(new TripleStore()); try { foreach (Triple t in manifest.GetTriplesWithSubjectPredicate(resultNode, utData)) { Console.WriteLine("Uses Result Default Graph File " + t.Object.ToString()); Graph g = new Graph(); UriLoader.Load(g, ((IUriNode)t.Object).Uri); g.BaseUri = null; resultDataset.AddGraph(g); } foreach (Triple t in manifest.GetTriplesWithSubjectPredicate(resultNode, utGraphData)) { Graph g = new Graph(); INode dataNode = manifest.GetTriplesWithSubjectPredicate(t.Object, utData).Concat(manifest.GetTriplesWithSubjectPredicate(t.Object, utGraph)).Select(x => x.Object).FirstOrDefault(); UriLoader.Load(g, ((IUriNode)dataNode).Uri); INode nameNode = manifest.GetTriplesWithSubjectPredicate(t.Object, rdfsLabel).Select(x => x.Object).FirstOrDefault(); g.BaseUri = new Uri(nameNode.ToString()); Console.WriteLine("Uses Result Named Graph File " + dataNode.ToString() + " named as " + nameNode.ToString()); resultDataset.AddGraph(g); } //Do this just to ensure that if the Result Dataset doesn't have a default unnamed graph it will //have one LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(resultDataset); } catch (Exception ex) { this.ReportError("Error Building Result Dataset", ex); Console.WriteLine("# Test Result - Unable to build Result Dataset (Test Indeterminate)"); testsEvaluationIndeterminate++; testsIndeterminate++; return 0; } Console.WriteLine(); //Now compare the two datasets to see if the tests passes foreach (Uri u in resultDataset.GraphUris) { if (dataset.HasGraph(u)) { if (!resultDataset[u].Equals(dataset[u])) { this.ShowGraphs(dataset[u], resultDataset[u]); Console.WriteLine("# Test Result - Expected Result Dataset Graph '" + this.ToSafeString(u) + "' is different from the Graph with that name in the Updated Dataset (Test Failed)"); testsEvaluationFailed++; testsFailed++; return -1; } } else { Console.WriteLine("# Test Result - Expected Result Dataset has Graph '" + this.ToSafeString(u) + "' which is not present in the Updated Dataset (Test Failed)"); testsEvaluationFailed++; testsFailed++; return -1; } } foreach (Uri u in dataset.GraphUris) { if (!resultDataset.HasGraph(u)) { Console.WriteLine("# Test Result - Updated Dataset has additional Graph '" + this.ToSafeString(u) + "' which is not present in the Expected Result Dataset (Test Failed)"); } } Console.WriteLine("# Test Result - Updated Dataset matches Expected Result Dataset (Test Passed)"); testsEvaluationPassed++; testsPassed++; return 1; } catch (Exception ex) { this.ReportError("Unexpected Error", ex); Console.WriteLine("# Test Result - Unexpected Error (Test Failed)"); testsEvaluationFailed++; testsFailed++; return -1; } }
public void SparqlGraphClause4() { String query = "SELECT * WHERE { GRAPH ?g { ?s ?p ?o } }"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); InMemoryDataset dataset = new InMemoryDataset(false); IGraph ex = new Graph(); FileLoader.Load(ex, "InferenceTest.ttl"); ex.BaseUri = new Uri("http://example.org/graph"); dataset.AddGraph(ex); IGraph def = new Graph(); dataset.AddGraph(def); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); Object results = processor.ProcessQuery(q); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); Assert.AreEqual(ex.Triples.Count, rset.Count, "Number of Results should have been equal to number of Triples"); } else { Assert.Fail("Did not get a SPARQL Result Set as expected"); } }
public void Cleanup() { this._parser = null; this._data = null; }
private void SparqlQueryThreadSafeEvaluationActual() { String query1 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/1> { ?s ?p ?o } }"; String query2 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/2> { ?s ?p ?o } }"; SparqlQuery q1 = this._parser.ParseFromString(query1); SparqlQuery q2 = this._parser.ParseFromString(query2); Assert.IsFalse(q1.UsesDefaultDataset, "Query 1 should not be thread safe"); Assert.IsFalse(q2.UsesDefaultDataset, "Query 2 should not be thread safe"); InMemoryDataset dataset = new InMemoryDataset(); Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); g.BaseUri = new Uri("http://example.org/1"); Graph h = new Graph(); h.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.Functions.LeviathanFunctionLibrary.ttl"); h.BaseUri = new Uri("http://example.org/2"); dataset.AddGraph(g); dataset.AddGraph(h); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); QueryWithGraphDelegate d = new QueryWithGraphDelegate(this.QueryWithGraph); IAsyncResult r1 = d.BeginInvoke(q1, processor, null, null); IAsyncResult r2 = d.BeginInvoke(q2, processor, null, null); WaitHandle.WaitAll(new WaitHandle[] { r1.AsyncWaitHandle, r2.AsyncWaitHandle }); IGraph gQuery = d.EndInvoke(r1); Assert.AreEqual(g, gQuery, "Query 1 Result not as expected"); IGraph hQuery = d.EndInvoke(r2); Assert.AreEqual(h, hQuery, "Query 2 Result not as expected"); Assert.AreNotEqual(g, h, "Graphs should not be different"); }
public void SparqlEvaluationGraphUnion() { SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromFile("graph-11.rq"); q.BaseUri = new Uri("file:///" + Environment.CurrentDirectory.Replace('\\', '/') + "/"); TripleStore store = new TripleStore(); Graph g = new Graph(); FileLoader.Load(g, "data-g1.ttl"); store.Add(g); Graph h = new Graph(); FileLoader.Load(h, "data-g2.ttl"); store.Add(h); Graph i = new Graph(); FileLoader.Load(i, "data-g3.ttl"); store.Add(i); Graph j = new Graph(); FileLoader.Load(j, "data-g4.ttl"); store.Add(j); InMemoryDataset dataset = new InMemoryDataset(store); q.AddDefaultGraph(g.BaseUri); q.AddNamedGraph(g.BaseUri); q.AddNamedGraph(h.BaseUri); q.AddNamedGraph(i.BaseUri); q.AddNamedGraph(j.BaseUri); SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap); Object results; //Try the full Query Console.WriteLine("Full Query"); Console.WriteLine(formatter.Format(q)); results = q.Evaluate(dataset); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); //SparqlRdfParser resultsParser = new SparqlRdfParser(new TurtleParser()); //SparqlResultSet expected = new SparqlResultSet(); //resultsParser.Load(expected, "graph-11.ttl"); //Console.WriteLine(); //Console.WriteLine("Expected Results"); //TestTools.ShowResults(expected); //Assert.AreEqual(rset, expected, "Result Sets should be equal"); } else { Assert.Fail("Didn't get a Result Set as expected"); } }
public void SparqlDatasetListGraphs() { InMemoryDataset dataset = new InMemoryDataset(new TripleStore()); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); Assert.IsTrue(dataset.GraphUris.Count() == 1, "Should be 1 Graph as the Update Processor should ensure a Default unnamed Graph exists"); }
/// <summary> /// Tries to load a SPARQL Dataset based on information from the Configuration Graph /// </summary> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> /// <param name="targetType">Target Type</param> /// <param name="obj">Output Object</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; INode storeNode; switch (targetType.FullName) { case InMemoryDataset: storeNode = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingStore)); if (storeNode == null) { obj = new InMemoryDataset(); } else { Object temp = ConfigurationLoader.LoadObject(g, storeNode); if (temp is IInMemoryQueryableStore) { obj = new InMemoryDataset((IInMemoryQueryableStore)temp); return true; } else { throw new DotNetRdfConfigurationException("Unable to load the In-Memory Dataset identified by the Node '" + objNode.ToString() + "' since the Object pointed to by the dnr:usingStore property could not be loaded as an object which implements the IInMemoryQueryableStore interface"); } } break; case InMemoryQuadDataset: storeNode = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingStore)); if (storeNode == null) { obj = new InMemoryQuadDataset(); } else { Object temp = ConfigurationLoader.LoadObject(g, storeNode); if (temp is IInMemoryQueryableStore) { obj = new InMemoryQuadDataset((IInMemoryQueryableStore)temp); return true; } else { throw new DotNetRdfConfigurationException("Unable to load the In-Memory Dataset identified by the Node '" + objNode.ToString() + "' since the Object pointed to by the dnr:usingStore property could not be loaded as an object which implements the IInMemoryQueryableStore interface"); } } break; } return false; }