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

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

            this.TestUpdate(store, expected, update);
        }
        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);
        }
Example #4
0
        static void Main(string[] args)
        {
            TripleStore ts = new TripleStore(@"http://localhost/SparqlQuery.yada")
            { QueryType = QueryType.RemoteSparqlStore };

            var query = from table in new RdfDataContext(ts).ForType<
        }
        private void EnsureTestResults(TripleStore store)
        {
            foreach (IGraph g in store.Graphs)
            {
                TestTools.ShowGraph(g);
                Console.WriteLine();
            }

            Assert.AreEqual(2, store.Graphs.Count, "Expected 2 Graphs");
            Assert.AreEqual(8, store.Graphs.Sum(g => g.Triples.Count), "Expected 4 Triples");

            IGraph def = store.Graph(null);
            IGraph named = store.Graph(new Uri("http://example.org/bnodes#graph"));

            HashSet<INode> subjects = new HashSet<INode>();
            foreach (Triple t in def.Triples)
            {
                subjects.Add(t.Subject);
            }
            foreach (Triple t in named.Triples)
            {
                subjects.Add(t.Subject);
            }

            Console.WriteLine("Subjects:");
            foreach (INode subj in subjects)
            {
                Console.WriteLine(subj.ToString() + " from Graph " + (subj.GraphUri != null ? subj.GraphUri.ToString() : "Default"));
            }
            Assert.AreEqual(4, subjects.Count, "Expected 4 distinct subjects");
        }
        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);
        }
Example #7
0
        public void SparqlUpdateLoad()
        {
            TripleStore store = new TripleStore();

            LoadCommand loadLondon = new LoadCommand(new Uri("http://dbpedia.org/resource/London"));
            LoadCommand loadSouthampton = new LoadCommand(new Uri("http://dbpedia.org/resource/Southampton"), new Uri("http://example.org"));

            store.ExecuteUpdate(loadLondon);
            store.ExecuteUpdate(loadSouthampton);

            Assert.AreEqual(2, store.Graphs.Count, "Should now be 2 Graphs in the Store");
            Assert.AreNotEqual(0, store.Triples.Count(), "Should be some Triples in the Store");

            foreach (IGraph g in store.Graphs)
            {
                foreach (Triple t in g.Triples)
                {
                    Console.Write(t.ToString());
                    if (g.BaseUri != null)
                    {
                        Console.WriteLine(" from " + g.BaseUri.ToString());
                    }
                    else
                    {
                        Console.WriteLine();
                    }
                }
            }
        }
 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);
 }
        public void CanConvertCannedDcsToRdf()
        {
            var store = new TripleStore();
            var converter = new DublinCoreConverter(store);

            converter.Convert(EnumerateCannedInput());

            converter.RdfDocument.ExportToN3("testoutputn3.rdf");
            converter.RdfDocument.ExportToRdfXml("testoutputXML.rdf");
        }
        public void ParsingStoreHandlerBlankNodesTriGActual()
        {
            EnsureTestData("test-bnodes.trig");

            TriGParser parser = new TriGParser();
            TripleStore store = new TripleStore();
            parser.Load(store, new StreamParams("test-bnodes.trig"));

            EnsureTestResults(store);
        }
 public void Query1()
 {
     var ts = new TripleStore(CreateMemoryStore());
     IQueryable<Track> qry = new RdfDataContext(ts).ForType<Track>();
     IQueryable<Track> q = from t in qry
                           where t.ArtistName == "Thomas Laqueur"
                           select t;
     var resultList = new List<Track>();
     resultList.AddRange(q);
 }
        private void EnsureTestData(String testFile)
        {
            if (!File.Exists(testFile))
            {
                TriGParser parser = new TriGParser();
                TripleStore store = new TripleStore();
                parser.Load(store, new TextReaderParams(new StringReader(TestFragment)));

                store.SaveToFile(testFile);
            }
        }
 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);
     }
 }
Example #14
0
 public void JosekiQueryWithProjection()
 {
     TripleStore ts = new TripleStore(@"http://localhost:2020/music");
     IRdfQuery<Track> qry = new RdfDataContext(ts).ForType<Track>();
     var q = from t in qry
                     where t.Year == "2007" &&
                     t.GenreName == "Rory Blyth: The Smartest Man in the World"
                     select new { t.Title, t.FileLocation };
     foreach (var track in q)
     {
         Console.WriteLine(track.Title + ": " + track.FileLocation);
     }
 }
         private void TestEmptyDatasetParsing(IStoreReader reader)
         {
             if (!File.Exists("empty.test"))
             {
                 FileStream temp = File.Create("empty.test");
                 temp.Close();
             }

             TripleStore store = new TripleStore();
             reader.Load(store, new VDS.RDF.Storage.Params.StreamParams("empty.test"));

             Assert.AreEqual(0, store.Graphs.Count, "Store should have no Graphs");
         }
        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 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));
        }
Example #18
0
        public static Object LoadFromFile(java.io.File f, string baseUri, org.openrdf.rio.RDFFormat rdff)
        {
            Object obj;

            if (rdff == dotSesameFormats.RDFFormat.N3)
            {
                obj = new Graph();
                if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri);
                FileLoader.Load((IGraph)obj, f.getPath(), new Notation3Parser());
            }
            else if (rdff == dotSesameFormats.RDFFormat.NTRIPLES)
            {
                obj = new Graph();
                if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri);
                FileLoader.Load((IGraph)obj, f.getPath(), new NTriplesParser());
            }
            else if (rdff == dotSesameFormats.RDFFormat.RDFXML)
            {
                obj = new Graph();
                if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri);
                FileLoader.Load((IGraph)obj, f.getPath(), new RdfXmlParser());
            }
            else if (rdff == dotSesameFormats.RDFFormat.TRIG)
            {
                obj = new TripleStore();
                TriGParser trig = new TriGParser();
                trig.Load((ITripleStore)obj, new StreamParams(f.getPath()));
            }
            else if (rdff == dotSesameFormats.RDFFormat.TRIX)
            {
                obj = new TripleStore();
                TriXParser trix = new TriXParser();
                trix.Load((ITripleStore)obj, new StreamParams(f.getPath()));
            }
            else if (rdff == dotSesameFormats.RDFFormat.TURTLE)
            {
                obj = new Graph();
                if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri);
                FileLoader.Load((IGraph)obj, f.getPath(), new TurtleParser());
            }
            else
            {
                throw new RdfParserSelectionException("The given Input Format is not supported by dotNetRDF");
            }

            return obj;
        }
        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));
        }
Example #21
0
        public void SparqlQueryTimeoutDuringProductLazy()
        {
            String      query = "SELECT * WHERE { ?s ?p ?o . ?x ?y ?z . ?a ?b ?c }";
            SparqlQuery q     = this._parser.ParseFromString(query);

            q.Timeout = 1;

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

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            store.Add(g);
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));

            Assert.Throws <RdfQueryTimeoutException>(() =>
            {
                processor.ProcessQuery(q);
            });
        }
Example #22
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();
        }
        public void GraphCollectionWebDemand2()
        {
            //Test that on-demand loading does not kick in for pre-existing graphs
            TripleStore store = new TripleStore(new WebDemandGraphCollection());

            Graph g = new Graph();
            Uri   u = new Uri("http://www.dotnetrdf.org/configuration#");

            g.LoadFromUri(u);
            g.BaseUri = u;

            Graph empty = new Graph();

            empty.BaseUri = g.BaseUri;
            store.Add(empty);

            Assert.IsTrue(store.HasGraph(g.BaseUri), "Graph Collection should contain the Graph");
            Assert.AreNotEqual(g, store[g.BaseUri], "Graphs should not be equal");
        }
Example #24
0
        public void TestAsyncQueryWithQueryCallback()
        {
            var store = new TripleStore();
            var g     = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            store.Add(g);
            var dataset = new InMemoryDataset(store, g.BaseUri);

            var processor = new LeviathanQueryProcessor(dataset);

            var wait   = new AutoResetEvent(false);
            var parser = new SparqlQueryParser();
            var query  = parser.ParseFromString(
                "SELECT * WHERE { ?instance a ?class }");
            var callbackInvoked = false;
            var syncResultSet   = processor.ProcessQuery(query) as SparqlResultSet;

            Assert.NotNull(syncResultSet);
            var syncResultCount = syncResultSet.Count;
            var resultSet       = new SparqlResultSet();
            var resultHandler   = new ResultSetHandler(resultSet);

            processor.ProcessQuery(null, resultHandler, query, (rdfHandler, rsetHandler, state) =>
            {
                try
                {
                    Assert.IsNotType <AsyncError>(state);
                    Assert.Equal("some state", state);
                }
                finally
                {
                    callbackInvoked = true;
                    wait.Set();
                }
            }, "some state");
            wait.WaitOne();
            var resultCount = resultSet.Count;

            Assert.True(callbackInvoked);
            Assert.True(resultCount > 0);
            Assert.Equal(syncResultCount, resultCount);
        }
Example #25
0
        public static IAnalysisEngine BuildAnalysisEngine(List <IDatabaseAccessDetector> dbAccessDetectors, IDatabaseFinder databaseFinder)
        {
            var logOutput = new LogOutput();

            // single instance services
            var typeService           = new TypeService();
            var tripleStore           = new TripleStore(typeService);
            var assignmentGraphWalker = new AssignmentGraphWalker(tripleStore);
            var delegateIndexer       = new DelegateIndexer(assignmentGraphWalker);
            var methodIndexer         = new MethodIndexer(delegateIndexer);

            var databaseResolver = new DatabaseResolver(assignmentGraphWalker, new AnalysisLogger(), dbAccessDetectors, databaseFinder);

            return(new AnalysisEngine(
                       new AssignmentGraphIndexer(new InstructionParser(logOutput), tripleStore, logOutput),
                       assignmentGraphWalker, methodIndexer, delegateIndexer,
                       new CallTreeWalker(methodIndexer, databaseResolver, logOutput),
                       typeService, logOutput));
        }
        private static IUriNode FindOwningSubject(this TripleStore store, IBlankNode blankNode)
        {
            INode result = blankNode;

            do
            {
                Triple triple = store.Triples.FirstOrDefault(item => item.Object.Equals(result));
                if (triple != null)
                {
                    result = triple.Subject;
                }
                else
                {
                    result = null;
                }
            }while ((result != null) && (result is IBlankNode));

            return((IUriNode)result);
        }
Example #27
0
        public void Setup()
        {
            _store = new TripleStore();
            _store.LoadTestFile("TriplesWithLiteralSubjects.trig");

            var container = new ServiceContainer();

            container.RegisterInstance <ITripleStore>(_store);

            IEntityContextFactory factory = new EntityContextFactory(container)
                                            .WithDefaultOntologies()
                                            .WithEntitySource <TripleStoreAdapter>()
                                            .WithMetaGraphUri(new Uri("http://app.magi/graphs"))
                                            .WithDependenciesInternal <Dependencies>();

            _typeCache = (TestCache)container.GetInstance <IRdfTypeCache>();

            _entityContext = factory.CreateContext();
        }
        public void SparqlPropertyPathEvaluationZeroOrMorePathReverse()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromFile("resources\\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.False(results.IsEmpty, "Results should not be 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 = ExecuteQuery(store, "ASK WHERE { GRAPH <dotnetrdf:default-graph> { ?s ?p ?o }}");

            if (results is SparqlResultSet)
            {
                Assert.False(((SparqlResultSet)results).Result);
            }
            else
            {
                Assert.True(false, "ASK Query did not return a SPARQL Result Set as expected");
            }
        }
Example #30
0
        /// <summary>
        /// Implementation of the task
        /// </summary>
        /// <returns></returns>
        protected sealed override TaskResult RunTaskInternal()
        {
            if (this._manager.UpdateSupported)
            {
                //Use a WriteToStoreHandler for direct writing
                this._canceller = new CancellableHandler(new WriteToStoreHandler(this._manager, this.GetTargetUri(), this._batchSize));
                if (this.HasBeenCancelled)
                {
                    this._canceller.Cancel();
                }

                //Wrap in a ChainedHandler to ensure we permit cancellation but also count imported triples
                ChainedHandler m = new ChainedHandler(new IRdfHandler[] { this._canceller, this._progress });
                this.ImportUsingHandler(m);
            }
            else
            {
                //Use a StoreHandler to load into memory and will do a SaveGraph() at the end
                TripleStore store = new TripleStore();
                this._canceller = new CancellableHandler(new StoreHandler(store));
                if (this.HasBeenCancelled)
                {
                    this._canceller.Cancel();
                }

                //Wrap in a ChainedHandler to ensure we permit cancellation but also count imported triples
                ChainedHandler m = new ChainedHandler(new IRdfHandler[] { this._canceller, this._progress });
                this.ImportUsingHandler(m);

                //Finally Save to the underlying Store
                foreach (IGraph g in store.Graphs)
                {
                    if (g.BaseUri == null)
                    {
                        g.BaseUri = this.GetTargetUri();
                    }
                    this._manager.SaveGraph(g);
                }
            }
            this.Information = this._counter.TripleCount + " Triple(s) in " + this._counter.GraphCount + " Graph(s) Imported";

            return(new TaskResult(true));
        }
Example #31
0
        public void ExecuteTripleStoreWithPatternsQueryReturnsDescriptionsForUrisAndVariables()
        {
            SparqlQuery query = new SparqlQuery("DESCRIBE ?var <http://example.com/other> WHERE {<http://example.com/subject> <http://example.com/pred> ?var }");

            TripleStore store = new MemoryTripleStore();

            store.Add(new Statement(new UriRef("http://example.com/subject"), new UriRef("http://example.com/pred"), new UriRef("http://example.com/obj")));
            store.Add(new Statement(new UriRef("http://example.com/obj"), new UriRef("http://example.com/pred"), new UriRef("http://example.com/thing")));
            store.Add(new Statement(new UriRef("http://example.com/other"), new UriRef("http://example.com/pred"), new UriRef("http://example.com/thing")));

            TripleStoreVerifier verifier = new TripleStoreVerifier();

            verifier.expect("<http://example.com/obj> <http://example.com/pred> <http://example.com/thing> .");
            verifier.expect("<http://example.com/other> <http://example.com/pred> <http://example.com/thing> .");

            TripleStore results = query.ExecuteTripleStore(store);

            Assert.IsTrue(verifier.verify(results), "Resulting triple store should contain describing triples");
        }
Example #32
0
        public void SparqlEvaluationGraphNonExistentUri()
        {
            String      query   = "SELECT * WHERE { GRAPH <http://example.org/noSuchGraph> { ?s ?p ?o } }";
            TripleStore store   = new TripleStore();
            Object      results = store.ExecuteQuery(query);

            if (results is SparqlResultSet)
            {
                TestTools.ShowResults(results);

                SparqlResultSet rset = (SparqlResultSet)results;
                Assert.IsTrue(rset.IsEmpty, "Result Set should be empty");
                Assert.AreEqual(3, rset.Variables.Count(), "Should still be 3 Variables even if no results");
            }
            else
            {
                Assert.Fail("Query should have returned a SPARQL Result Set");
            }
        }
Example #33
0
        public static SparqlResultSet PerformQuery(string q, Graph g)
        {
            SparqlParameterizedString queryString = new SparqlParameterizedString();

            queryString.Namespaces.AddNamespace("ldp", new Uri("http://www.w3.org/ns/ldp#"));
            queryString.Namespaces.AddNamespace("dct", new Uri("http://purl.org/dc/terms/"));
            queryString.CommandText = q;
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       query  = parser.ParseFromString(queryString);

            TripleStore store = new TripleStore();

            store.Add(g);

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

            return(results);
        }
        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 (writer is IMultiThreadedWriter)
            {
                ((IMultiThreadedWriter)writer).UseMultiThreadedWriting = useMultiThreaded;
            }
            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]);
            }
        }
Example #35
0
        private void EnsureTestData(String file)
        {
            if (this._original == null)
            {
                Graph g = new Graph();
                g.Assert(g.CreateBlankNode(), g.CreateUriNode(UriFactory.Create("http://example.org/predicate")), g.CreateLiteralNode("literal", "en-123"));
                g.Assert(g.CreateBlankNode(), g.CreateUriNode(UriFactory.Create("http://example.org/predicate")), g.CreateLiteralNode("literal", "en-gb-us"));
                g.Assert(g.CreateBlankNode(), g.CreateUriNode(UriFactory.Create("http://example.org/predicate")), g.CreateLiteralNode("literal", "en-123-abc"));
                this._original = g;

                this._store = new TripleStore();
                this._store.Add(this._original);
            }

            if (!File.Exists(file))
            {
                MimeTypeDefinition def = MimeTypesHelper.GetDefinitions(MimeTypesHelper.GetMimeTypes(Path.GetExtension(file))).FirstOrDefault();
                if (def != null)
                {
                    if (def.CanWriteRdf)
                    {
                        this._original.SaveToFile(file);
                    }
                    else if (def.CanWriteRdfDatasets)
                    {
                        this._store.SaveToFile(file);
                    }
                    else
                    {
                        Assert.Fail("Unable to ensure test data");
                    }
                }
                else
                {
                    Assert.Fail("Unsupported file type");
                }
            }
            else
            {
                Assert.Fail("Unable to ensure test data");
            }
        }
Example #36
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");
            }
        }
Example #37
0
        public void SparqlUpdateChangesNotReflectedInOriginalGraph2()
        {
            //Test Case originally submitted by Tomasz Pluskiewicz

            // given
            IGraph sourceGraph = new Graph();

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

            IGraph expectedGraph = new Graph();

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

            TripleStore store = new TripleStore();

            store.Add(sourceGraph);
            ISparqlDataset dataset = new InMemoryDataset(store, sourceGraph.BaseUri);

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

            processor.ProcessCommandSet(cmds);

            Assert.Single(dataset.Graphs);

            IGraph g = dataset.Graphs.First();

            Assert.Equal(2, g.Triples.Count);
            Assert.True(ReferenceEquals(g, sourceGraph), "Result Graph should be the Source Graph");
            Assert.Equal(2, sourceGraph.Triples.Count);
            Assert.Equal(expectedGraph, sourceGraph);
        }
        private void EnsureLeviathanReady()
        {
            if (this._dataset == null)
            {
                TripleStore store = new TripleStore();
                Graph       g     = new Graph();
                g.LoadFromFile("resources\\InferenceTest.ttl");
                store.Add(g);

                this._dataset = new InMemoryDataset(store);
            }
            if (this._leviathan == null)
            {
                this._leviathan = new LeviathanQueryProcessor(this._dataset);
            }
            if (this._explainer == null)
            {
                this._explainer = new ExplainQueryProcessor(this._dataset, ExplanationLevel.Default);
            }
        }
        private TripleStore CreateNewTripleStore(IDictionary <string, string> graphs)
        {
            var store = new TripleStore();

            foreach (var graph in graphs)
            {
                var g = new VDS.RDF.Graph(true)
                {
                    BaseUri = new Uri(graph.Value)
                };

                var ttlparser = new TurtleParser();
                ttlparser.Load(g, AppDomain.CurrentDomain.BaseDirectory + $"Setup/Graphs/{graph.Key}");
                store.Add(g);
            }
            ;

            // TODO: Check if usesGraph is in graphGraph
            return(store);
        }
Example #40
0
        public void RoundtripsDatetimeLiterals(string dateTimeValue, string datatype)
        {
            using (var store = new TripleStore())
            {
                var jsonLd = $@"
{{
    ""http://example.com/1"": {{
        ""@type"": ""{datatype}"",
        ""@value"": ""{dateTimeValue}""
    }}
}}
";
                store.LoadFromString(jsonLd, new JsonLdParser());

                var result = store.Graphs.Single().Triples.Single().Object.As <ILiteralNode>();

                Assert.Equal(dateTimeValue, result.Value);
                Assert.Equal(datatype, result.DataType.AbsoluteUri);
            }
        }
Example #41
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();
        }
Example #42
0
        public void ParsingGZipDatasetByGZipStreamAuto()
        {
            foreach (String filename in this._autoDatasetTestFiles)
            {
                TripleStore store = new TripleStore();

                String ext = MimeTypesHelper.GetTrueFileExtension(filename);
                ext = ext.Substring(1);
                MimeTypeDefinition def = MimeTypesHelper.Definitions.Where(d => d.CanParseRdfDatasets && d.SupportsFileExtension(ext)).FirstOrDefault();
                if (def == null)
                {
                    Assert.Fail("Failed to find MIME Type Definition for File Extension ." + ext);
                }

                IStoreReader reader = def.GetRdfDatasetParser();
                reader.Load(store, new StreamReader(new GZipStream(new FileStream(filename, FileMode.Open, FileAccess.Read), CompressionMode.Decompress)));

                Assert.AreEqual(this._g, store.Graphs.First(), "Graphs for file " + filename + " were not equal");
            }
        }
Example #43
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();
        }
Example #44
0
        private static void Test(string query, bool isNamedGraph, int expectedCount)
        {
            IGraph graph = new Graph();

            if (isNamedGraph)
            {
                graph.BaseUri = new Uri("http://g");
            }
            new TurtleParser().Load(graph, new StringReader(TestData));

            IInMemoryQueryableStore store = new TripleStore();

            store.Add(graph);
            IQueryableStorage storage = new InMemoryManager(store);

            using (SparqlResultSet resultSet = (SparqlResultSet)storage.Query(query))
            {
                Assert.Equal(expectedCount, resultSet.Count);
            }
        }
Example #45
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;
                }
            }
        }
Example #46
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);
            }
        }
        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");
        }
Example #48
0
        public void SparqlEvaluationMultipleOptionals2()
        {
            TripleStore store = new TripleStore();

            store.LoadFromFile("resources\\multiple-options.trig");

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       query  = parser.ParseFromFile("resources\\multiple-optionals-alternate.rq");

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store);
            Object results = processor.ProcessQuery(query);

            if (results is SparqlResultSet)
            {
                TestTools.ShowResults(results);
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
Example #49
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());
            }
        }
Example #50
0
        public void SparqlUpdateModify()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "resources\\InferenceTest.ttl");
            g.BaseUri = null;
            store.Add(g);

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

            Assert.NotEmpty(store.GetTriplesWithPredicate(rdfType));

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

            store.ExecuteUpdate(cmds);

            Assert.Empty(store.GetTriplesWithPredicate(rdfType));
        }
Example #51
0
        public void SparqlUpdateLoadQuads4()
        {
            var tripleStore = new TripleStore();

            String g1 = Path.GetFullPath(@"resources\core-421\g1.nq").Replace('\\', '/');
            String g2 = Path.GetFullPath(@"resources\core-421\g2.nq").Replace('\\', '/');

            tripleStore.ExecuteUpdate("LOAD <file:///" + g1 + "> into graph <http://test.org/user>");
            tripleStore.ExecuteUpdate("LOAD <file:///" + g2 + "> into graph <http://test.org/prodList/>");
            Assert.Equal(3, tripleStore.Triples.Count());
            Assert.Equal(3, tripleStore.Graphs.Count);

            tripleStore.SaveToFile("core-421.nq", new NQuadsWriter());

            var newStore = new TripleStore();

            newStore.LoadFromFile("core-421.nq", new NQuadsParser());

            Assert.Equal(3, newStore.Triples.Count());
            Assert.Equal(2, newStore.Graphs.Count);
        }
Example #52
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");
        }
        private void ParsingStoreHandlerNQuadsExplicitActual()
        {
            this.EnsureTestData("test.nq");

            TripleStore store = new TripleStore();
            StreamParams ps = new StreamParams("test.nq", Encoding.ASCII);

            NQuadsParser parser = new NQuadsParser();
            parser.Load(new StoreHandler(store), ps);

            Assert.IsTrue(store.HasGraph(new Uri("http://www.dotnetrdf.org/configuration#")), "Configuration Vocab Graph should have been parsed from Dataset");
            Graph configOrig = new Graph();
            configOrig.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            IGraph config = store.Graph(new Uri("http://www.dotnetrdf.org/configuration#"));
            Assert.AreEqual(configOrig, config, "Configuration Vocab Graphs should have been equal");

            Assert.IsTrue(store.HasGraph(new Uri("http://www.dotnetrdf.org/leviathan#")), "Leviathan Function Library Graph should have been parsed from Dataset");
            Graph lvnOrig = new Graph();
            lvnOrig.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.Functions.LeviathanFunctionLibrary.ttl");
            IGraph lvn = store.Graph(new Uri("http://www.dotnetrdf.org/leviathan#"));
            Assert.AreEqual(lvnOrig, lvn, "Leviathan Function Library Graphs should have been equal");

        }
        public void SparqlFunctionsNow()
        {
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromFile("now01.rq");

            Console.WriteLine("ToString Output:");
            Console.WriteLine(q.ToString());
            Console.WriteLine();

            SparqlFormatter formatter = new SparqlFormatter();
            Console.WriteLine("SparqlFormatter Output:");
            Console.WriteLine(formatter.Format(q));

            TripleStore store = new TripleStore();
            SparqlResultSet results = q.Evaluate(store) as SparqlResultSet;
            if (results != null)
            {
                Assert.IsTrue(results.Result, "Result should be true");
            }
            else
            {
                Assert.Fail("Expected a non-null result");
            }
        }
        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");
            }
        }
        public void SparqlUpdateTimeout()
        {
            String update = "CREATE GRAPH <http://example.org/1>; LOAD <http://www.dotnetrdf.org/configuration#>; CREATE GRAPH <http://example.org/2>";
            SparqlUpdateCommandSet cmds = this._parser.ParseFromString(update);
            cmds.Timeout = 1;

            TripleStore store = new TripleStore();
            LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store);
            try
            {
                processor.ProcessCommandSet(cmds);
                Assert.Fail("Expected a SparqlUpdateTimeoutException");
            }
            catch (SparqlUpdateTimeoutException timeoutEx)
            {
                TestTools.ReportError("Timeout", timeoutEx, false);
                Console.WriteLine();
                Console.WriteLine("Execution Time: " + cmds.UpdateExecutionTime.Value.ToString());

                Assert.IsFalse(store.HasGraph(new Uri("http://example.org/1")), "Graph 1 should not exist");
                Assert.IsFalse(store.HasGraph(new Uri("http://example.org/2")), "Graph 2 should not exist");

            }
        }
Example #57
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 SparqlEvaluationGraphNonExistentUri()
        {
            String query = "SELECT * WHERE { GRAPH <http://example.org/noSuchGraph> { ?s ?p ?o } }";
            TripleStore store = new TripleStore();
            Object results = store.ExecuteQuery(query);

            if (results is SparqlResultSet)
            {
                TestTools.ShowResults(results);

                SparqlResultSet rset = (SparqlResultSet)results;
                Assert.IsTrue(rset.IsEmpty, "Result Set should be empty");
                Assert.AreEqual(3, rset.Variables.Count(), "Should still be 3 Variables even if no results");
            }
            else
            {
                Assert.Fail("Query should have returned a SPARQL Result Set");
            }
        }
        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 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);
                }
            }
        }