private void EnsureTestData(String testFile)
        {
            if (!File.Exists(testFile))
            {
                TripleStore store = new TripleStore();
                Graph g = new Graph();
                g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
                store.Add(g);
                Graph h = new Graph();
                h.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.Functions.LeviathanFunctionLibrary.ttl");
                store.Add(h);

                store.SaveToFile(testFile);
            }
        }
        private void TestExplainProcessor(String query)
        {
            if (this._processor == null)
            {
                TripleStore store = new TripleStore();
                Graph g = new Graph();
                g.LoadFromFile("InferenceTest.ttl");
                g.BaseUri = null;
                store.Add(g);

                this._processor = new ExplainQueryProcessor(store);
            }

            SparqlQuery q = this._parser.ParseFromString(query);
            Object results;
            Console.WriteLine("Input Query:");
            Console.WriteLine(this._formatter.Format(q));
            Console.WriteLine();

            Console.WriteLine("Explanation with Default Options (Simulated):");
            this._processor.ExplanationLevel = ExplanationLevel.DefaultSimulation;
            results = this._processor.ProcessQuery(q);

            Console.WriteLine();
            Console.WriteLine("Explanation with Default Options:");
            this._processor.ExplanationLevel = ExplanationLevel.Default;
            results = this._processor.ProcessQuery(q);

            Console.WriteLine();
            Console.WriteLine("Explanation with Full Options:");
            this._processor.ExplanationLevel = ExplanationLevel.Full;
            results = this._processor.ProcessQuery(q);
        }
        private void TestUpdate(IGraph data, IGraph expected, String update)
        {
            TripleStore store = new TripleStore();
            store.Add(data);

            this.TestUpdate(store, expected, update);
        }
        public void SparqlFunctionsIsNumeric()
        {
            Graph g = new Graph();
            IUriNode subj = g.CreateUriNode(new Uri("http://example.org/subject"));
            IUriNode pred = g.CreateUriNode(new Uri("http://example.org/predicate"));

            g.Assert(subj, pred, (12).ToLiteral(g));
            g.Assert(subj, pred, g.CreateLiteralNode("12"));
            g.Assert(subj, pred, g.CreateLiteralNode("12", new Uri(XmlSpecsHelper.XmlSchemaDataTypeNonNegativeInteger)));
            g.Assert(subj, pred, g.CreateLiteralNode("12", new Uri(XmlSpecsHelper.XmlSchemaDataTypeNonPositiveInteger)));
            g.Assert(subj, pred, g.CreateLiteralNode("1200", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)));
            g.Assert(subj, pred, ((byte)50).ToLiteral(g));
            g.Assert(subj, pred, g.CreateLiteralNode("-50", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)));
            g.Assert(subj, pred, g.CreateLiteralNode("-50", new Uri(XmlSpecsHelper.XmlSchemaDataTypeUnsignedByte)));
            g.Assert(subj, pred, g.CreateUriNode(new Uri("http://example.org")));

            TripleStore store = new TripleStore();
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString("SELECT ?obj (IsNumeric(?obj) AS ?IsNumeric) WHERE { ?s ?p ?obj }");

            Object results = store.ExecuteQuery(q);

            Assert.IsTrue(results is SparqlResultSet, "Result should be a SPARQL Result Set");
            TestTools.ShowResults(results);
        }
        private void TestConstruct(IGraph data, IGraph expected, String query)
        {
            TripleStore store = new TripleStore();
            store.Add(data);

            this.TestConstruct(store, expected, query);
        }
        private void TestConstruct(IGraph data, IGraph expected, String query)
        {
            TripleStore store = new TripleStore();

            store.Add(data);

            this.TestConstruct(store, expected, query);
        }
Beispiel #7
0
        public void SparqlViewAndReasonerInteraction1()
        {
            TripleStore store = new TripleStore();
            SparqlView  view  = new SparqlView("CONSTRUCT { ?s a ?type } WHERE { GRAPH ?g { ?s a ?type } }", store);

            view.BaseUri = new Uri("http://example.org/view");
            store.Add(view);

            Console.WriteLine("SPARQL View Empty");
            TestTools.ShowGraph(view);
            Console.WriteLine();

            //Load a Graph into the Store to cause the SPARQL View to update
            Graph g = new Graph();

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

            Thread.Sleep(500);
            if (view.Triples.Count == 0)
            {
                view.UpdateView();
            }

            Console.WriteLine("SPARQL View Populated");
            TestTools.ShowGraph(view);
            Console.WriteLine();

            Assert.True(view.Triples.Count > 0, "View should have updated to contain some Triples");
            int lastCount = view.Triples.Count;

            //Apply an RDFS reasoner
            StaticRdfsReasoner reasoner = new StaticRdfsReasoner();

            reasoner.Initialise(g);
            store.AddInferenceEngine(reasoner);

            Thread.Sleep(200);
            if (view.Triples.Count == lastCount)
            {
                view.UpdateView();
            }
            Console.WriteLine("SPARQL View Populated after Reasoner added");
            TestTools.ShowGraph(view);
        }
Beispiel #8
0
        public string MakeSparqlQueryAndReturnGraphAsJsonLdString(string sparqlQuery)
        {
            var result = _repository.ExecuteQuery(sparqlQuery) as IGraph;
            var ts     = new TripleStore();

            ts.Add(result);
            return(StringWriter.Write(ts, new JsonLdWriter()));
        }
Beispiel #9
0
        public void WritingSparqlXmlWithSpecialCharacters()
        {
            TripleStore store = new TripleStore();

            store.Add(new Graph());
            Graph g = new Graph();

            g.BaseUri = new Uri("http://example.org/graph");
            INode subj = g.CreateBlankNode();
            INode pred = g.CreateUriNode(new Uri("http://example.org/predicate"));
            INode obj1 = g.CreateLiteralNode("with & ampersand");
            INode obj2 = g.CreateLiteralNode("with < tags > ");

            g.Assert(subj, pred, obj1);
            g.Assert(subj, pred, obj2);
            store.Add(g);

            Object results = store.ExecuteQuery("SELECT * WHERE { ?s ?p ?o }");

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset   = (SparqlResultSet)results;
                SparqlXmlWriter writer = new SparqlXmlWriter();
                writer.Save(rset, "temp.srx");

                SparqlXmlParser parser = new SparqlXmlParser();
                SparqlResultSet rset2  = new SparqlResultSet();
                parser.Load(rset2, "temp.srx");

                rset.Trim();
                Console.WriteLine("Original Results");
                TestTools.ShowResults(rset);
                Console.WriteLine();

                rset2.Trim();
                Console.WriteLine("Serializes and Parsed Results");
                TestTools.ShowResults(rset2);
                Console.WriteLine();

                Assert.AreEqual(rset, rset2, "Result Sets should be equal");
            }
            else
            {
                Assert.Fail("Query did not return a Result Set as expected");
            }
        }
        private void TestUpdate(IGraph data, IGraph expected, String update)
        {
            TripleStore store = new TripleStore();

            store.Add(data);

            this.TestUpdate(store, expected, update);
        }
Beispiel #11
0
        public void AddTripleStoreWithNoCommonNodes()
        {
            UriRef node1 = new  UriRef("any:node1");
            UriRef node2 = new  UriRef("any:node2");
            UriRef node3 = new  UriRef("any:node3");
            UriRef node4 = new  UriRef("any:node4");
            UriRef node5 = new  UriRef("any:node5");
            UriRef node6 = new  UriRef("any:node6");

            UriRef predicate1 = new UriRef("any:predicate1");
            UriRef predicate2 = new UriRef("any:predicate2");
            UriRef predicate3 = new UriRef("any:predicate3");

            Statement statement1 = new Statement(node1, predicate1, node2);
            Statement statement2 = new Statement(node3, predicate2, node4);
            Statement statement3 = new Statement(node5, predicate3, node6);

            TripleStore firstStore = MakeNewTripleStore();

            firstStore.Add(statement1);

            TripleStore secondStore = MakeNewTripleStore();

            secondStore.Add(statement2);
            secondStore.Add(statement3);

            firstStore.Add(secondStore);
            TripleStoreVerifier verifierFirst = new TripleStoreVerifier();

            verifierFirst.expect("<any:node1> <any:predicate1> <any:node2> .");
            verifierFirst.expect("<any:node3> <any:predicate2> <any:node4> .");
            verifierFirst.expect("<any:node5> <any:predicate3> <any:node6> .");

            Assert.IsTrue(verifierFirst.verify(firstStore), "first triple store includes triples from second");

            TripleStoreVerifier verifierSecond = new TripleStoreVerifier();

            verifierSecond.expect("<any:node3> <any:predicate2> <any:node4> .");
            verifierSecond.expect("<any:node5> <any:predicate3> <any:node6> .");

            Assert.IsTrue(verifierSecond.verify(secondStore), "second triple store is unchanged");

            firstStore.Clear();
            secondStore.Clear();
        }
Beispiel #12
0
        public void CloneReturnsIndependentTripleStore()
        {
            TripleStore store = MakeNewTripleStore();

            store.Add(new Statement(new BlankNode(), new UriRef("http://example.com/pred"), new BlankNode()));

            TripleStore clone = (TripleStore)store.Clone();
            int         cloneNodeCountBefore     = clone.NodeCount;
            int         cloneResourceCountBefore = clone.ResourceCount;

            store.Add(new Statement(new BlankNode(), new UriRef("http://example.com/pred"), new BlankNode()));
            Assert.AreEqual(cloneNodeCountBefore, clone.NodeCount, "Clone node count is unchanged");
            Assert.AreEqual(cloneResourceCountBefore, clone.ResourceCount, "Clone resource count is unchanged");

            store.Clear();
            Assert.AreEqual(cloneNodeCountBefore, clone.NodeCount, "Clone node count is unchanged after Clearing original");
            Assert.AreEqual(cloneResourceCountBefore, clone.ResourceCount, "Clone resource count is unchanged after Clearing original");
        }
Beispiel #13
0
        public TripleStore LoadStore(string owlFilePath)
        {
            var store = new TripleStore();
            var g     = new Graph();

            FileLoader.Load(g, owlFilePath);
            store.Add(g);
            return(store);
        }
 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);
 }
Beispiel #15
0
        public void SparqlQuery()
        {
            TripleStore store = new TripleStore();
            var         g     = new Graph();

            var parser = new NTriplesParser();

            parser.Load(g, new StringReader(
                            @"<http://example.org/a> <http://example.org/b> <http://example.org/c>.
  <http://example.org/a> <http://example.org/b> <http://example.org/d>.
  <http://example.org/a> <http://example.org/b> <http://example.org/e>.
  <http://example.org/d> <http://example.org/f> <http://example.org/g>."));

            store.Add(g);

            // Normal SPARQL results ARE NOT rdf data. But a rows of bindings.
            Object results = store.ExecuteQuery("SELECT * WHERE {?s ?p ?o}");

            if (results is SparqlResultSet)
            {
                var rset = (SparqlResultSet)results;
                Assert.AreEqual(4, rset.Count);

                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result.ToString());
                }
            }

            // SPARQL can be used to construct RDF as a result of the query. This can be loaded into a graph
            SparqlQueryParser sparqlparser = new SparqlQueryParser();
            SparqlQuery       query        = sparqlparser.ParseFromString("CONSTRUCT { ?s ?p ?o } WHERE {?s ?p ?o}");

            results = store.ExecuteQuery(query);
            if (results is IGraph)
            {
                IGraph gr = (IGraph)results;
                foreach (Triple t in gr.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
            }

            // SPARQL works by matching patterns
            results = store.ExecuteQuery("SELECT * WHERE {<http://example.org/a> ?p ?o}");
            if (results is SparqlResultSet)
            {
                var rset = (SparqlResultSet)results;
                Assert.AreEqual(3, rset.Count);

                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result.ToString());
                }
            }
        }
Beispiel #16
0
        public void Contains()
        {
            TripleStore store = MakeNewTripleStore();


            store.Add(new Statement(new UriRef("ex:subj"), new UriRef("ex:pred"), new UriRef("ex:obj")));

            Assert.IsTrue(store.Contains(new Statement(new UriRef("ex:subj"), new UriRef("ex:pred"), new UriRef("ex:obj"))));
            store.Clear();
        }
Beispiel #17
0
        public void Setup()
        {
            SetupNamespaceMap();
            _tripleStore    = new TripleStore();
            _defaultGraph   = CreateGraph(null);
            _inferences     = CreateGraph(new Uri("http://industrialinference.com/inferred/"));
            _contradictions = CreateGraph(new Uri("http://industrialinference.com/contradictions/"));
            _tripleStore.Add(_defaultGraph);
            _tripleStore.Add(_inferences);
            _tripleStore.Add(_contradictions);
            var qp      = new LeviathanQueryProcessor(_tripleStore);
            var up      = new LeviathanUpdateProcessor(_tripleStore);
            var builder = new ContainerBuilder();

            builder.RegisterType <InferenceEngine>().AsImplementedInterfaces();
            builder.Register <ISparqlQueryProcessor>(_ => qp);
            builder.Register <ISparqlUpdateProcessor>(_ => up);
            _container = builder.Build();
        }
        private void TestWriter(IStoreWriter writer, IStoreReader reader, bool useMultiThreaded, int compressionLevel)
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            g.BaseUri = null;
            store.Add(g);
            g = new Graph();
            g.LoadFromFile("resources\\InferenceTest.ttl");
            g.BaseUri = new Uri("http://example.org/graph");
            store.Add(g);
            g = new Graph();
            g.LoadFromFile(@"resources\cyrillic.rdf");
            g.BaseUri = new Uri("http://example.org/cyrillic");
            store.Add(g);

            if (writer is ICompressingWriter)
            {
                ((ICompressingWriter)writer).CompressionLevel = compressionLevel;
            }
#if !NETCOREAPP2_0
            if (writer is IMultiThreadedWriter)
            {
                ((IMultiThreadedWriter)writer).UseMultiThreadedWriting = useMultiThreaded;
            }
#endif
            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            writer.Save(store, strWriter);

            Console.WriteLine(strWriter.ToString());

            Assert.NotEqual(strWriter.ToString(), String.Empty);

            TripleStore store2 = new TripleStore();
            reader.Load(store2, new System.IO.StringReader(strWriter.ToString()));

            foreach (IGraph graph in store.Graphs)
            {
                Assert.True(store2.HasGraph(graph.BaseUri), "Parsed Stored should have contained serialized graph");
                Assert.Equal(graph, store2[graph.BaseUri]);
            }
        }
        public void GraphCollectionBasic1()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            store.Add(g);

            Assert.IsTrue(store.HasGraph(g.BaseUri), "Graph Collection should contain the Graph");
            Assert.AreEqual(g, store[g.BaseUri], "Graphs should be equal");
        }
Beispiel #20
0
        public void InteropSemWebInMemoryStoreConversion()
        {
            //Set up a Store and load 3 Graphs into it
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);
            g = new Graph();
            FileLoader.Load(g, "Turtle.ttl");
            store.Add(g);
            g = new Graph();
            g.Assert(new Triple(g.CreateUriNode(new Uri("http://example.org/#this")), g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)), g.CreateUriNode(new Uri("http://example.org/Graph"))));
            store.Add(g);

            InMemoryStoreSource source = new InMemoryStoreSource(store);

            //Put this all into a SemWeb MemoryStore
            MemoryStore mem = new MemoryStore();

            source.Select(mem);

            SemWebConsolePrinter printer = new SemWebConsolePrinter();

            mem.Select(printer);

            //Read it back into a dotNetRDF TripleStore
            InMemoryStoreSource source2 = new InMemoryStoreSource(new TripleStore());

            mem.Select(source2);

            //Check the two stores are equivalent
            IInMemoryQueryableStore store2 = source2.Store;

            foreach (IGraph graph in store.Graphs)
            {
                String baseUri = (graph.BaseUri == null) ? String.Empty : graph.BaseUri.ToString();
                Assert.IsTrue(store2.HasGraph(graph.BaseUri), "Second Store has Graph '" + baseUri + "' missing");

                Assert.AreEqual(graph, store2.Graph(graph.BaseUri), "Graph '" + baseUri + "' was not the same Graph in both Stores");
            }
        }
Beispiel #21
0
        public ResultAccessTests()
        {
            Graph g = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            TripleStore store = new TripleStore();

            store.Add(g);
            this._dataset   = new InMemoryDataset(store);
            this._processor = new LeviathanQueryProcessor(this._dataset);
        }
        public string MakeSparqlQueryAndReturnGraphAsJsonLdString(string sparqlQuery)
        {
            var         parser     = new SparqlQueryParser();
            SparqlQuery tupleQuery = parser.ParseFromString(sparqlQuery);
            var         processor  = new LeviathanQueryProcessor(_repository);
            var         result     = processor.ProcessQuery(tupleQuery) as IGraph;
            var         ts         = new TripleStore();

            ts.Add(result);
            return(StringWriter.Write(ts, new JsonLdWriter()));
        }
Beispiel #23
0
        /// <summary>
        /// Loads a serialized graph from the given stream into the current store. See allowed <see cref="RdfSerializationFormat">formats</see>.
        /// </summary>
        /// <param name="stream">Stream containing a serialized graph</param>
        /// <param name="graphUri">Uri of the graph in this store</param>
        /// <param name="format">Allowed formats</param>
        /// <param name="update">Pass false if you want to overwrite the existing data. True if you want to add the new data to the existing.</param>
        /// <returns></returns>
        public override Uri Read(Stream stream, Uri graphUri, RdfSerializationFormat format, bool update)
        {
            using (TextReader reader = new StreamReader(stream))
            {
                IGraph graph = new Graph();

                TryParse(reader, graph, format);

                graph.BaseUri = graphUri;

                if (!update)
                {
                    _store.Remove(graphUri);
                }

                _store.Add(graph, update);

                return(graphUri);
            }
        }
        public DescribeAlgorithms()
        {
            this._parser = new SparqlQueryParser();
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromFile("resources\\describe-algos.ttl");
            store.Add(g);
            this._data      = new InMemoryDataset(store);
            this._processor = new LeviathanQueryProcessor(this._data);
        }
Beispiel #25
0
 private void EnsureTestData()
 {
     if (this._data == null)
     {
         TripleStore store = new TripleStore();
         Graph       g     = new Graph();
         g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
         store.Add(g);
         this._data = new InMemoryDataset(store, g.BaseUri);
     }
 }
Beispiel #26
0
        private ISparqlDataset GetDataset(List <IGraph> gs, Uri defaultGraphUri)
        {
            TripleStore store = new TripleStore();

            foreach (IGraph g in gs)
            {
                store.Add(g, false);
            }

            return(new InMemoryDataset(store, defaultGraphUri));
        }
Beispiel #27
0
        public void SparqlJsonResultSet()
        {
            Console.WriteLine("Tests that JSON Parser parses language specifiers correctly");

            String query = "PREFIX rdfs: <" + NamespaceMapper.RDFS + ">\nSELECT DISTINCT ?comment WHERE {?s rdfs:comment ?comment}";

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

            FileLoader.Load(g, "json.owl");
            store.Add(g);

            Object results = store.ExecuteQuery(query);

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;

                //Serialize to both XML and JSON Results format
                SparqlXmlWriter xmlwriter = new SparqlXmlWriter();
                xmlwriter.Save(rset, "results.xml");
                SparqlJsonWriter jsonwriter = new SparqlJsonWriter();
                jsonwriter.Save(rset, "results.json");

                //Read both back in
                SparqlXmlParser xmlparser = new SparqlXmlParser();
                SparqlResultSet r1        = new SparqlResultSet();
                xmlparser.Load(r1, "results.xml");
                Console.WriteLine("Result Set after XML serialization and reparsing contains:");
                foreach (SparqlResult r in r1)
                {
                    Console.WriteLine(r.ToString());
                }
                Console.WriteLine();

                SparqlJsonParser jsonparser = new SparqlJsonParser();
                SparqlResultSet  r2         = new SparqlResultSet();
                jsonparser.Load(r2, "results.json");
                Console.WriteLine("Result Set after JSON serialization and reparsing contains:");
                foreach (SparqlResult r in r2)
                {
                    Console.WriteLine(r.ToString());
                }
                Console.WriteLine();

                Assert.AreEqual(r1, r2, "Results Sets should be equal");

                Console.WriteLine("Result Sets were equal as expected");
            }
            else
            {
                Assert.Fail("Query did not return a Result Set");
            }
        }
        public FullTextSparqlTests2()
        {
            this._nsmap = new NamespaceMapper();
            this._nsmap.AddNamespace("pf", new Uri(FullTextHelper.FullTextMatchNamespace));
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            store.Add(g);
            this._dataset = new InMemoryDataset(store, true);
        }
        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);
            this._processor = new LeviathanQueryProcessor(this._data);
        }
Beispiel #30
0
        public void AddStatementDistinguishesDifferentBlankNodeInstancesForSubjects()
        {
            TripleStore store = MakeNewTripleStore();

            BlankNode node1 = new BlankNode();
            BlankNode node2 = new BlankNode();

            store.Add(new Statement(node1, new UriRef("http://example.com/pred"), new UriRef("http://example.com/obj1")));
            store.Add(new Statement(node1, new UriRef("http://example.com/pred"), new UriRef("http://example.com/obj2")));
            store.Add(new Statement(node2, new UriRef("http://example.com/pred"), new UriRef("http://example.com/obj2")));

            TripleStoreVerifier verifier = new TripleStoreVerifier();

            verifier.expect("_:node1 <http://example.com/pred> <http://example.com/obj1> .");
            verifier.expect("_:node1 <http://example.com/pred> <http://example.com/obj2> .");
            verifier.expect("_:node2 <http://example.com/pred> <http://example.com/obj2> .");

            Assert.IsTrue(verifier.verify(store));
            store.Clear();
        }
Beispiel #31
0
        public void AddDistinguishesDifferentBlankNodeInstances()
        {
            Node theSubject      = new NodeStub("http://example.com/subj");
            Arc  thePredicate    = new UriRef("http://example.com/pred");
            Node theFirstObject  = new UriRef("http://example.com/obj1");
            Node theSecondObject = new UriRef("http://example.com/obj2");

            TripleStore store = MakeNewTripleStore();

            store.Add(new Statement(new BlankNode(), new UriRef("http://example.com/pred"), new UriRef("http://example.com/obj1")));
            store.Add(new Statement(new BlankNode(), new UriRef("http://example.com/pred"), new UriRef("http://example.com/obj2")));

            TripleStoreVerifier verifier = new TripleStoreVerifier();

            verifier.expect("_:node1 <http://example.com/pred> <http://example.com/obj1> .");
            verifier.expect("_:node2 <http://example.com/pred> <http://example.com/obj2> .");

            Assert.IsTrue(verifier.verify(store));
            store.Clear();
        }
        public void GraphCollectionBasic2()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            store.Add(g);

            Assert.IsTrue(store.HasGraph(g.BaseUri), "Graph Collection should contain the Graph");
            Assert.AreEqual(g, store[g.BaseUri], "Graphs should be equal");
        }
 private void EnsureTestData()
 {
     if (this._data == null)
     {
         TripleStore store = new TripleStore();
         Graph g = new Graph();
         g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
         store.Add(g);
         this._data = new InMemoryDataset(store);
     }
 }
Beispiel #34
0
        static void CustomQuery()
        {
            Uri prefixRDF  = new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
            Uri prefixFilm = new Uri("http://www.semprog.com/film#");

            //IGraph g = new Graph();                 //Load triples from file OWL
            //g.LoadFromFile("film-ontology.owl");
            //g.BaseUri = null; //!
            IGraph g = new VDS.RDF.Graph();             //Load triples from server (OWL)

            RdfsReasoner reasoner = new RdfsReasoner(); //Apply reasoner

            reasoner.Initialise(g);
            reasoner.Apply(g);


            g.BaseUri = null;   //!!!!!!!!
            TripleStore store = new TripleStore();

            store.Add(g);

            SparqlParameterizedString queryString = new SparqlParameterizedString();

            queryString.Namespaces.AddNamespace("rdf", prefixRDF);
            queryString.Namespaces.AddNamespace("film", prefixFilm);
            queryString.CommandText = "SELECT ?who WHERE { ?who rdf:type film:Person }";

            string sparql = "";

            sparql = File.ReadAllText("sparql1.txt");

            SparqlQueryParser parser = new SparqlQueryParser();
            //SparqlQuery query = parser.ParseFromString(queryString.ToString());
            SparqlQuery query = parser.ParseFromString(sparql);

            Console.WriteLine(query.ToAlgebra());
            Console.WriteLine(query.ToString());

            //ISparqlQueryProcessor processor = new LeviathanQueryProcessor(store);   //process query
            //SparqlResultSet results = processor.ProcessQuery(query) as SparqlResultSet;

            ISparqlQueryProcessor processor = new MirageQueryProcessor(mapping);//new LeviathanQueryProcessor(store);   //process query
            string results = processor.ProcessQuery(query) as string;

            Console.WriteLine(results);
            //if (results is SparqlResultSet)
            //{
            //    SparqlResultSet rset = (SparqlResultSet)results;
            //    foreach (SparqlResult result in rset)
            //    {
            //        Console.WriteLine(result);
            //    }
            //}
        }
Beispiel #35
0
        public static void ApplyInference(IGraph graph, IGraph schema)
        {
            string inverseOf = @"
                PREFIX owl: <http://www.w3.org/2002/07/owl#>
                CONSTRUCT { ?y ?q ?x }
                WHERE { ?p owl:inverseOf ?q .
                        ?x ?p ?y . }
            ";

            var parser = new SparqlQueryParser();

            var rules = new List <SparqlQuery>();

            rules.Add(parser.ParseFromString(inverseOf));

            var store = new TripleStore();

            store.Add(graph, true);
            store.Add(schema, true);

            var queryProcessor = new LeviathanQueryProcessor(store);

            while (true)
            {
                int before = store.Triples.Count();

                foreach (var rule in rules)
                {
                    IGraph inferred = (IGraph)queryProcessor.ProcessQuery(rule);
                    //store.Add(inferred);
                    graph.Merge(inferred);
                }

                int after = store.Triples.Count();

                if (after == before)
                {
                    break;
                }
            }
        }
Beispiel #36
0
        public void GetStatementEnumeratorReturnsResourceStatementInstances()
        {
            TripleStore store = MakeNewTripleStore();

            store.Add(new Statement(new BlankNode(), new UriRef("http://example.com/pred"), new UriRef("http://example.com/obj1")));

            IEnumerator statementEnum = store.GetStatementEnumerator();

            Assert.IsTrue(statementEnum.MoveNext(), "Enumerator has first statement");
            Assert.IsTrue(statementEnum.Current is ResourceStatement, "Enumerator returns a ResourceStatement");
            store.Clear();
        }
        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.True(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.False(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");
        }
Beispiel #38
0
        public void SparqlViewDescribe()
        {
            try
            {
                TripleStore store = new TripleStore();
                SparqlView view = new SparqlView("DESCRIBE <http://example.org/vehicles/FordFiesta>", store);
                view.BaseUri = new Uri("http://example.org/view");
                store.Add(view);

                Console.WriteLine("SPARQL View Empty");
                TestTools.ShowGraph(view);
                Console.WriteLine();

                //Load a Graph into the Store to cause the SPARQL View to update
                Graph g = new Graph();
                FileLoader.Load(g, "InferenceTest.ttl");
                g.BaseUri = new Uri("http://example.org/data");
                store.Add(g);

                Thread.Sleep(200);
                if (view.Triples.Count == 0) view.UpdateView();

                Console.WriteLine("SPARQL View Populated");
                TestTools.ShowGraph(view);

                Assert.IsTrue(view.Triples.Count > 0, "View should have updated to contain some Triples");
            }
            catch (RdfQueryException queryEx)
            {
                TestTools.ReportError("Query Error", queryEx, true);
            }
            catch (RdfException ex)
            {
                TestTools.ReportError("Error", ex, true);
            }
        }
        public void WritingSparqlXmlWithNulls()
        {
            TripleStore store = new TripleStore();
            store.Add(new Graph());
            Graph g = new Graph();
            g.BaseUri = new Uri("http://example.org/graph");
            store.Add(g);

            Object results = store.ExecuteQuery("SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }");
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                SparqlXmlWriter writer = new SparqlXmlWriter();
                writer.Save(rset, "temp.srx");

                SparqlXmlParser parser = new SparqlXmlParser();
                SparqlResultSet rset2 = new SparqlResultSet();
                parser.Load(rset2, "temp.srx");

                rset.Trim();
                Console.WriteLine("Original Results");
                TestTools.ShowResults(rset);
                Console.WriteLine();

                rset2.Trim();
                Console.WriteLine("Serializes and Parsed Results");
                TestTools.ShowResults(rset2);
                Console.WriteLine();

                Assert.AreEqual(rset, rset2, "Result Sets should be equal");
            }
            else
            {
                Assert.Fail("Query did not return a Result Set as expected");
            }
        }
        private void WritingTriGActual()
        {
            Graph g = new Graph();
            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            g.BaseUri = null;
            TripleStore store = new TripleStore();
            store.Add(g);

            TriGWriter writer = new TriGWriter();
            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            writer.Save(store, new TextWriterParams(strWriter));

            Console.WriteLine(strWriter.ToString());

            Assert.IsFalse(strWriter.ToString().Equals(String.Empty));
        }
        public void SparqlDefaultGraphExists2()
        {
            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);

            Object results = store.ExecuteQuery("ASK WHERE { GRAPH <dotnetrdf:default-graph> { ?s ?p ?o }}");
            if (results is SparqlResultSet)
            {
                Assert.IsTrue(((SparqlResultSet)results).Result);
            }
            else
            {
                Assert.Fail("ASK Query did not return a SPARQL Result Set as expected");
            }
        }
        public void WritingTriGUncompressedSingleThreaded()
        {
            Graph g = new Graph();
            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            g.BaseUri = null;
            TripleStore store = new TripleStore();
            store.Add(g);

            TriGWriter writer = new TriGWriter();
            writer.UseMultiThreadedWriting = false;
            writer.CompressionLevel = WriterCompressionLevel.None;
            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            writer.Save(store, new TextWriterParams(strWriter));

            Console.WriteLine(strWriter.ToString());

            Assert.IsFalse(strWriter.ToString().Equals(String.Empty));
        }
Beispiel #43
0
        public void GraphEventBubbling()
        {
            try
            {
                this._graphAdded = false;
                this._graphRemoved = false;
                this._graphChanged = false;

                //Create Store and Graph add attach handlers to Store
                TripleStore store = new TripleStore();
                Graph g = new Graph();
                store.GraphAdded += this.HandleGraphAdded;
                store.GraphRemoved += this.HandleGraphRemoved;
                store.GraphChanged += this.HandleGraphChanged;

                //Add the Graph to the Store which should fire the GraphAdded event
                store.Add(g);
                Assert.IsTrue(this._graphAdded, "GraphAdded event of the Triple Store should have fired");

                //Assert a Triple
                INode s = g.CreateBlankNode();
                INode p = g.CreateUriNode("rdf:type");
                INode o = g.CreateUriNode("rdfs:Class");
                Triple t = new Triple(s, p, o);
                g.Assert(t);
                Assert.IsTrue(this._graphChanged, "GraphChanged event of the Triple Store should have fired");

                //Retract the Triple
                this._graphChanged = false;
                g.Retract(t);
                Assert.IsTrue(this._graphChanged, "GraphChanged event of the Triple Store should have fired");

                //Remove the Graph from the Store which should fire the GraphRemoved event
                store.Remove(g.BaseUri);
                Assert.IsTrue(this._graphRemoved, "GraphRemoved event of the Triple Store should have fired");
            }
            catch (Exception ex)
            {
                TestTools.ReportError("Error", ex, true);
            }
        }
Beispiel #44
0
        public void SparqlUpdateInsertDataWithSkolemBNodes()
        {
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            store.Add(g);

            String prefixes = "PREFIX rdf: <" + NamespaceMapper.RDF + ">\n PREFIX xsd: <" + NamespaceMapper.XMLSCHEMA + ">\n PREFIX ex: <http://example.org/>\n PREFIX rdl: <http://example.org/roles>\n PREFIX tpl: <http://example.org/template/>\n";
            String insert = prefixes + "INSERT DATA { " + InsertPatterns1 + "}";
            Console.WriteLine(insert.Replace("_:template","<_:template>"));
            Console.WriteLine();
            store.ExecuteUpdate(insert.Replace("_:template", "<_:template>"));
            insert = prefixes + "INSERT DATA {" + InsertPatterns2 + "}";
            Console.WriteLine(insert);
            Console.WriteLine();
            store.ExecuteUpdate(insert);

            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
            }
        }
        /// <summary>
        /// Applies reasoning on the Input Graph materialising the generated Triples in the Output Graph
        /// </summary>
        /// <param name="input">Input Graph</param>
        /// <param name="output">Output Graph</param>
        public void Apply(IGraph input, IGraph output)
        {
            TripleStore store = new TripleStore();
            store.Add(input);
            if (!ReferenceEquals(input, output))
            {
                store.Add(output, true);
            }

            //Apply each rule in turn
            foreach (String[] rule in this._rules)
            {
                //Build the final version of the rule text for the given input and output
                StringBuilder ruleText = new StringBuilder();

                //If there's a Base URI on the Output Graph need a WITH clause
                if (output.BaseUri != null)
                {
                    ruleText.AppendLine("WITH <" + this._formatter.FormatUri(output.BaseUri) + ">");
                }
                ruleText.AppendLine(rule[0]);
                //If there's a Base URI on the Input Graph need a USING clause
                if (input.BaseUri != null)
                {
                    ruleText.AppendLine("USING <" + this._formatter.FormatUri(input.BaseUri) + ">");
                }
                ruleText.AppendLine(rule[1]);

                ISyntaxValidationResults results = this._validator.Validate(ruleText.ToString());
                if (results.IsValid)
                {
                    store.ExecuteUpdate((SparqlUpdateCommandSet)results.Result);
                }
            }
        }
Beispiel #46
0
        public void SparqlUpdateModify()
        {
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            g.BaseUri = null;
            store.Add(g);

            IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));

            Assert.AreNotEqual(0, store.GetTriplesWithPredicate(rdfType).Count(), "Store should contain some rdf:type Triples");

            String update = "DELETE {?s a ?type} WHERE {?s a ?type}";
            SparqlUpdateParser parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds = parser.ParseFromString(update);
            store.ExecuteUpdate(cmds);

            Assert.AreEqual(0, store.GetTriplesWithPredicate(rdfType).Count(), "Store should contain no rdf:type Triples after DELETE command executes");
        }
Beispiel #47
0
        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 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");
            }
        }
Beispiel #49
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));
            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));
            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");            
        }
Beispiel #50
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(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");
        }
        /// <summary>
        /// Updates a Graph in the Stardog Store
        /// </summary>
        /// <param name="graphUri">Uri of the Graph to update</param>
        /// <param name="additions">Triples to be added</param>
        /// <param name="removals">Triples to be removed</param>
        /// <remarks>
        /// Removals happen before additions
        /// </remarks>
        public void UpdateGraph(Uri graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals)
        {
            String tID = null;
            try
            {
                //Get a Transaction ID, if there is no active Transaction then this operation will be auto-committed
                tID = (this._activeTrans.Value != null) ? this._activeTrans.Value : this.BeginTransaction();

                //First do the Removals
                if (removals != null)
                {
                    if (removals.Any())
                    {
                        HttpWebRequest request = this.CreateRequest(this._kb + "/" + tID + "/remove", MimeTypesHelper.Any, "POST", new Dictionary<string, string>());
                        request.ContentType = MimeTypesHelper.TriG[0];

                        //Save the Data to be removed as TriG to the Request Stream
                        TripleStore store = new TripleStore();
                        Graph g = new Graph();
                        g.Assert(removals);
                        g.BaseUri = graphUri;
                        store.Add(g);
                        this._writer.Save(store, new StreamParams(request.GetRequestStream()));

                        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        {
                            response.Close();
                        }
                    }
                }

                //Then do the Additions
                if (additions != null)
                {
                    if (additions.Any())
                    {
                        HttpWebRequest request = this.CreateRequest(this._kb + "/" + tID + "/add", MimeTypesHelper.Any, "POST", new Dictionary<string, string>());
                        request.ContentType = MimeTypesHelper.TriG[0];

                        //Save the Data to be removed as TriG to the Request Stream
                        TripleStore store = new TripleStore();
                        Graph g = new Graph();
                        g.Assert(additions);
                        g.BaseUri = graphUri;
                        store.Add(g);
                        this._writer.Save(store, new StreamParams(request.GetRequestStream()));

                        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        {
                            response.Close();
                        }
                    }
                }

                //Commit Transaction only if in auto-commit mode (active transaction will be null)
                if (this._activeTrans.Value == null)
                {
                    try
                    {
                        this.CommitTransaction(tID);
                    }
                    catch (Exception ex)
                    {
                        throw new RdfStorageException("Stardog failed to commit a Transaction", ex);
                    }
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null) Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
#endif
                //Rollback Transaction only if got as far as creating a Transaction
                //and in auto-commit mode
                if (tID != null)
                {
                    if (this._activeTrans.Value == null)
                    {
                        try
                        {
                            this.RollbackTransaction(tID);
                        }
                        catch (Exception ex)
                        {
                            throw new RdfStorageException("Stardog failed to rollback a Transaction", ex);
                        }
                    }
                }

                throw new RdfStorageException("A HTTP Error occurred while trying to update a Graph in the Store", webEx);
            }
        }
        public void SparqlStreamingBgpSelectEvaluation()
        {
            //Get the Data we want to query
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);
            //g = new Graph();
            //FileLoader.Load(g, "noise.ttl");
            //store.Add(g);

            Console.WriteLine(store.Triples.Count() + " Triples in Store");

            //Create the Triple Pattern we want to query with
            IUriNode fordFiesta = g.CreateUriNode(new Uri("http://example.org/vehicles/FordFiesta"));
            IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
            IUriNode rdfsLabel = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "label"));
            IUriNode speed = g.CreateUriNode(new Uri("http://example.org/vehicles/Speed"));
            IUriNode carClass = g.CreateUriNode(new Uri("http://example.org/vehicles/Car"));

            TriplePattern allTriples = new TriplePattern(new VariablePattern("?s"), new VariablePattern("?p"), new VariablePattern("?o"));
            TriplePattern allTriples2 = new TriplePattern(new VariablePattern("?x"), new VariablePattern("?y"), new VariablePattern("?z"));
            TriplePattern tp1 = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(rdfType), new NodeMatchPattern(carClass));
            TriplePattern tp2 = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(speed), new VariablePattern("?speed"));
            TriplePattern tp3 = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(rdfsLabel), new VariablePattern("?label"));
            TriplePattern novars = new TriplePattern(new NodeMatchPattern(fordFiesta), new NodeMatchPattern(rdfType), new NodeMatchPattern(carClass));
            TriplePattern novars2 = new TriplePattern(new NodeMatchPattern(fordFiesta), new NodeMatchPattern(rdfsLabel), new NodeMatchPattern(carClass));
            FilterPattern blankSubject = new FilterPattern(new UnaryExpressionFilter(new IsBlankFunction(new VariableExpressionTerm("?s"))));
            List<List<ITriplePattern>> tests = new List<List<ITriplePattern>>()
            {
                new List<ITriplePattern>() { },
                new List<ITriplePattern>() { allTriples },
                new List<ITriplePattern>() { allTriples, allTriples2 },
                new List<ITriplePattern>() { tp1 },
                new List<ITriplePattern>() { tp1, tp2 },
                new List<ITriplePattern>() { tp1, tp3 },
                new List<ITriplePattern>() { novars },
                new List<ITriplePattern>() { novars, tp1 },
                new List<ITriplePattern>() { novars, tp1, tp2 },
                new List<ITriplePattern>() { novars2 },
                new List<ITriplePattern>() { tp1, blankSubject }
            };

            foreach (List<ITriplePattern> tps in tests)
            {
                Console.WriteLine(tps.Count + " Triple Patterns in the Query");
                foreach (ITriplePattern tp in tps)
                {
                    Console.WriteLine(tp.ToString());
                }
                Console.WriteLine();

                ISparqlAlgebra select = new Bgp(tps);
                ISparqlAlgebra selectOptimised = new LazyBgp(tps, 10);

                //Evaluate with timings
                Stopwatch timer = new Stopwatch();
                TimeSpan unopt, opt;
                timer.Start();
                BaseMultiset results1 = select.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store)));
                timer.Stop();
                unopt = timer.Elapsed;
                timer.Reset();
                timer.Start();
                BaseMultiset results2 = selectOptimised.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store)));
                timer.Stop();
                opt = timer.Elapsed;

                Console.WriteLine("SELECT = " + results1.GetType().ToString() + " (" + results1.Count + " Results) in " + unopt.ToString());
                Console.WriteLine("SELECT Optimised = " + results2.GetType().ToString() + " (" + results2.Count + " Results) in " + opt.ToString());

                Console.WriteLine();
                Console.WriteLine("Optimised Results");
                foreach (Set s in results2.Sets)
                {
                    Console.WriteLine(s.ToString());
                }

                Assert.IsTrue(results1.Count >= results2.Count, "Optimised Select should have produced as many/fewer results than Unoptimised Select");

                Console.WriteLine();
            }
        }
        public void SparqlBgpEvaluation()
        {
            //Prepare the Store
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "Turtle.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(@"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT * WHERE {?s ?p ?o . ?s rdfs:label ?label}");
            Object testResult = store.ExecuteQuery(q);

            ISparqlAlgebra testAlgebra = q.ToAlgebra();

            if (testResult is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)testResult;
                Console.WriteLine(rset.Count + " Results");
                foreach (SparqlResult r in rset) 
                {
                    Console.WriteLine(r.ToString());
                }
                Console.WriteLine();
            }

            //Create some Triple Patterns
            TriplePattern t1 = new TriplePattern(new VariablePattern("?s"), new VariablePattern("?p"), new VariablePattern("?o"));
            TriplePattern t2 = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(g.CreateUriNode("rdfs:label")), new VariablePattern("?label"));
            TriplePattern t3 = new TriplePattern(new VariablePattern("?x"), new VariablePattern("?y"), new VariablePattern("?z"));
            TriplePattern t4 = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(g.CreateUriNode(":name")), new VariablePattern("?name"));

            //Build some BGPs
            Bgp selectNothing = new Bgp();
            Bgp selectAll = new Bgp(t1);
            Bgp selectLabelled = new Bgp(new List<ITriplePattern>() { t1, t2 });
            Bgp selectAllDisjoint = new Bgp(new List<ITriplePattern>() { t1, t3 });
            Bgp selectLabels = new Bgp(t2);
            Bgp selectNames = new Bgp(t4);
            //LeftJoin selectOptionalNamed = new LeftJoin(selectAll, new Optional(selectNames));
            LeftJoin selectOptionalNamed = new LeftJoin(selectAll, selectNames);
            Union selectAllUnion = new Union(selectAll, selectAll);
            Union selectAllUnion2 = new Union(selectAllUnion, selectAll);
            Filter selectAllUriObjects = new Filter(selectAll, new UnaryExpressionFilter(new IsUriFunction(new VariableExpressionTerm("o"))));

            //Test out the BGPs
            //Console.WriteLine("{}");
            //this.ShowMultiset(selectNothing.Evaluate(new SparqlEvaluationContext(null, store)));

            //Console.WriteLine("{?s ?p ?o}");
            //this.ShowMultiset(selectAll.Evaluate(new SparqlEvaluationContext(null, store)));

            //Console.WriteLine("{?s ?p ?o . ?s rdfs:label ?label}");
            //SparqlEvaluationContext context = new SparqlEvaluationContext(null, store);
            //this.ShowMultiset(selectLabelled.Evaluate(context));
            //SparqlResultSet lvnResult = new SparqlResultSet(context);

            //Console.WriteLine("{?s ?p ?o . ?x ?y ?z}");
            //this.ShowMultiset(selectAllDisjoint.Evaluate(new SparqlEvaluationContext(null, store)));

            //Console.WriteLine("{?s ?p ?o . OPTIONAL {?s :name ?name}}");
            //this.ShowMultiset(selectOptionalNamed.Evaluate(new SparqlEvaluationContext(null, store)));

            Console.WriteLine("{{?s ?p ?o} UNION {?s ?p ?o}}");
            this.ShowMultiset(selectAllUnion.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store))));

            Console.WriteLine("{{?s ?p ?o} UNION {?s ?p ?o} UNION {?s ?p ?o}}");
            this.ShowMultiset(selectAllUnion2.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store))));

            Console.WriteLine("{?s ?p ?o FILTER (ISURI(?o))}");
            this.ShowMultiset(selectAllUriObjects.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store))));
        }
        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 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 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 SparqlPropertyPathParser()
        {
            //Load our test data
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            List<String> testQueries = new List<string>();
            String rdfsPrefix = "PREFIX rdfs: <" + NamespaceMapper.RDFS + ">\n";

            //Cardinality Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf* <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf+ <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf? <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2,4} <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2,} <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{,4} <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2} <http://example.org/vehicles/Vehicle>}");

            //Simple Inverse Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?type ^a ?entity}");

            //Sequence Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf / rdfs:subClassOf <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2} / rdfs:subClassOf <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf / rdfs:subClassOf{2} <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass a / rdfs:subClassOf <http://example.org/vehicles/Plane>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?vehicle a ^ rdfs:subClassOf <http://example.org/vehicles/Plane>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass a / ^ rdfs:subClassOf <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?entity a ^ a ?type}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?entity a ^ a / rdfs:subClassOf <http://example.org/vehicles/GroundVehicle>}");


            //Alternative Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf | a <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass (rdfs:subClassOf | a) | rdfs:someProperty <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf | a | rdfs:someProperty <http://example.org/vehicles/Vehicle>}");

            SparqlQueryParser parser = new SparqlQueryParser();

            foreach (String query in testQueries)
            {
                //Parse the Query and output to console
                SparqlQuery q = parser.ParseFromString(query);
                Console.WriteLine(q.ToString());

                //Now we'll try and evaluate it (if this is possible)
                try
                {
                    Object results = store.ExecuteQuery(q);

                    Console.WriteLine("Evaluated OK");
                    TestTools.ShowResults(results);
                    Console.WriteLine();
                }
                catch (RdfQueryException queryEx)
                {
                    Console.WriteLine("Unable to evaluate:");
                    Console.WriteLine(queryEx.Message);
                    Console.WriteLine(queryEx.StackTrace);
                }
            }
        }
        /// <summary>
        /// Saves a Graph into the Store (see remarks for notes on merge/overwrite behaviour)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// <para>
        /// If the Graph has no URI then the contents will be appended to the Store's Default Graph.  If the Graph has a URI then existing Graph associated with that URI will be replaced.  To append to a named Graph use the <see cref="StardogConnector.UpdateGraph">UpdateGraph()</see> method instead
        /// </para>
        /// </remarks>
        public void SaveGraph(IGraph g)
        {
            String tID = null;
            try
            {
                //Get a Transaction ID, if there is no active Transaction then this operation will be auto-committed
                tID = (this._activeTrans.Value != null) ? this._activeTrans.Value : this.BeginTransaction();

                HttpWebRequest request = this.CreateRequest(this._kb + "/" + tID + "/add", MimeTypesHelper.Any, "POST", new Dictionary<string,string>());
                request.ContentType = MimeTypesHelper.TriG[0];

                if (g.BaseUri != null)
                {
                    try
                    {
                        this.DeleteGraph(g.BaseUri);
                    }
                    catch (Exception ex)
                    {
                        throw new RdfStorageException("Unable to save a Named Graph to the Store as this requires deleting any existing Named Graph with this name which failed, see inner exception for more detail", ex);
                    }
                }
                
                //Save the Data as TriG to the Request Stream
                TripleStore store = new TripleStore();
                store.Add(g);
                this._writer.Save(store, new StreamParams(request.GetRequestStream()));

#if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugRequest(request);
                }
#endif
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    //If we get here then it was OK
                    response.Close();
                }

                //Commit Transaction only if in auto-commit mode (active transaction will be null)
                if (this._activeTrans.Value == null)
                {
                    try
                    {
                        this.CommitTransaction(tID);
                    }
                    catch (Exception ex)
                    {
                        throw new RdfStorageException("Stardog failed to commit a Transaction", ex);
                    }
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null) Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
#endif

                //Rollback Transaction only if got as far as creating a Transaction
                //and in auto-commit mode
                if (tID != null)
                {
                    if (this._activeTrans.Value == null)
                    {
                        try
                        {
                            this.RollbackTransaction(tID);
                        }
                        catch (Exception ex)
                        {
                            throw new RdfStorageException("Stardog failed to rollback a Transaction", ex);
                        }
                    }
                }

                throw new RdfStorageException("A HTTP Error occurred while trying to save a Graph to the Store", webEx);
            }
        }
Beispiel #59
0
        public void SparqlUpdateMoveCommand3()
        {
            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("MOVE DEFAULT TO GRAPH <http://example.org/destination>");

            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);
            processor.ProcessCommandSet(commands);

            g = store.HasGraph(null) ? store.Graph(null) : null;
            h = store.Graph(new Uri("http://example.org/destination"));
            Assert.IsFalse(h.IsEmpty, "Destination Graph should not be empty");
            Assert.IsFalse(g == null, "Default Graph should still exist");
            Assert.IsTrue(g.IsEmpty, "Source Graph (the Default Graph) should be Empty");

            Graph orig = new Graph();
            FileLoader.Load(orig, "InferenceTest.ttl");
            Assert.AreEqual(orig, h, "Destination Graph should be equal to the original contents of the Source Graph");
        }
Beispiel #60
0
        public void SparqlUpdateAddCommand()
        {
            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 = 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("ADD GRAPH <http://example.org/source> TO GRAPH <http://example.org/destination>");

            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);
            processor.ProcessCommandSet(commands);

            g = store.Graph(new Uri("http://example.org/source"));
            h = store.Graph(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.IsTrue(h.HasSubGraph(g), "Destination Graph should have Source Graph as a subgraph");
        }