Example #1
0
        public void SparqlBindLazy()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT ?triple WHERE { ?s ?p ?o . BIND(fn:concat(STR(?s), ' ', STR(?p), ' ', STR(?o)) AS ?triple) } LIMIT 1";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 1, "Expected exactly 1 results");
                Assert.IsTrue(rset.All(r => r.HasValue("triple")), "All Results should have had a value for ?triple");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        public IEnumerable<IDataObject> BindRdfDataObjects(XDocument rdfXmlDocument,
                                                           IList<OrderingDirection> orderingDirections)
        {
            var g = new Graph();
#if PORTABLE || WINDOWS_PHONE
			var parser = new RdfXmlParser(RdfXmlParserMode.Streaming);
			// This is pretty nasty, having to deserialize only to go through parsing again
			parser.Load(g, new System.IO.StringReader(rdfXmlDocument.ToString()));
#else
			var parser = new RdfXmlParser(RdfXmlParserMode.DOM);
            parser.Load(g, rdfXmlDocument.AsXmlDocument());
#endif
            var p = new VDS.RDF.Query.LeviathanQueryProcessor(new InMemoryDataset(g));
            var queryString = MakeOrderedResourceQuery(orderingDirections);
            var sparqlParser = new SparqlQueryParser();
            var query = sparqlParser.ParseFromString(queryString);
            var queryResultSet = p.ProcessQuery(query) as VDS.RDF.Query.SparqlResultSet;
            foreach (var row in queryResultSet.Results)
            {
                INode uriNode;
                if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode)
                {
                    yield return BindRdfDataObject(uriNode as IUriNode, g);
                }
            }
        } 
Example #3
0
 public void TestParser()
 {
     const string exp = "select ?t where { ?t a ?tt }";
     var parser = new SparqlQueryParser();
     var query = parser.ParseFromString(exp);            
     Assert.IsNotNull(query);
 }
        public void SparqlDefaultGraphExists3()
        {
            SqlDataset dataset = new SqlDataset(new MicrosoftSqlStoreManager("localhost", "unit_test", "example", "password"));

            //Create Default Graph only if required
            if (!dataset.HasGraph(null))
            {
                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")));
                dataset.AddGraph(g);
                dataset.Flush();
            }

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString("ASK WHERE { GRAPH ?g { ?s ?p ?o }}");
            LeviathanQueryProcessor lvn = new LeviathanQueryProcessor(dataset);
            Object results = lvn.ProcessQuery(q);
            if (results is SparqlResultSet)
            {
                Assert.IsTrue(((SparqlResultSet)results).Result);
            }
            else
            {
                Assert.Fail("ASK Query did not return a SPARQL Result Set as expected");
            }

            dataset.Flush();
        }
        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 #6
0
        public fclsInspect(SparqlQuery query, long parseTime, String origQuery)
        {
            InitializeComponent();

            this.lblParseTime.Text = "Took " + parseTime + "ms to parse";
            this.txtQuery.Text = this._formatter.Format(query);
            this.txtAlgebra.Text = query.ToAlgebra().ToString();

            //Compute the actual syntax compatability
            SparqlQueryParser parser = new SparqlQueryParser();
            parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_0;
            try
            {
                SparqlQuery q = parser.ParseFromString(origQuery);
                this.lblSyntaxCompatability.Text += " SPARQL 1.0 (Standard)";
            }
            catch
            {
                try
                {
                    parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_1;
                    SparqlQuery q = parser.ParseFromString(origQuery);
                    this.lblSyntaxCompatability.Text += " SPARQL 1.1 (Current Working Draft Standard)";
                }
                catch
                {
                    parser.SyntaxMode = SparqlQuerySyntax.Extended;
                    SparqlQuery q = parser.ParseFromString(origQuery);
                    this.lblSyntaxCompatability.Text += " SPARQL 1.1 (Implementation specific extensions)";
                }
            }
        }
 public SparqlResult ExecuteQuery(SparqlQueryContext queryContext, IList<string> datasetGraphUris)
 {
     var parser = new SparqlQueryParser();
     var query = parser.ParseFromString(queryContext.SparqlQuery);
     var sparqlResults = _queryProcessor.ProcessQuery(query);
     return new SparqlResult(sparqlResults, queryContext);
 }
Example #8
0
        public void SparqlGroupByAssignmentExpression()
        {
            String query = "SELECT ?s ?sum WHERE { ?s ?p ?o } GROUP BY ?s (1 + 2 AS ?sum)";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

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

            QueryableGraph g = new QueryableGraph();
            FileLoader.Load(g, "InferenceTest.ttl");

            Object results = g.ExecuteQuery(q);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                TestTools.ShowResults(rset);

                Assert.IsTrue(rset.All(r => r.HasValue("s") && r.HasValue("sum")), "All Results should have a ?s and a ?sum variable");
            }
            else
            {
                Assert.Fail("Didn't get a Result Set as expected");
            }
        }
        public void SparqlAlgebraReverseSimple()
        {
            List<String> tests = new List<string>()
            {
                "SELECT * WHERE { ?s ?p ?o }",
                "SELECT ?s WHERE { ?s ?p ?o }",
                "SELECT ?p ?o WHERE { ?s ?p ?o }",
                "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT (fn:concat(?s, ?p) AS ?string) WHERE {?s ?p ?o}",
                "SELECT * WHERE {?s ?p ?o . ?o ?x ?y }",
                "SELECT * WHERE {?s ?p ?o . OPTIONAL {?o ?x ?y} }",
                "SELECT * WHERE {?s ?p ?o . OPTIONAL {?o ?x ?y . FILTER(BOUND(?s)) } }"
            };

            SparqlQueryParser parser = new SparqlQueryParser();
            foreach (String test in tests)
            {
                Console.WriteLine("Test Input:");
                Console.WriteLine(test);
                Console.WriteLine();
                Console.WriteLine("Parsed Query:");
                SparqlQuery q = parser.ParseFromString(test);
                Console.WriteLine(q.ToString());
                Console.WriteLine();
                Console.WriteLine("Algebra:");
                Console.WriteLine(q.ToAlgebra().ToString());
                Console.WriteLine();
                Console.WriteLine("Algebra Reverse Transformed to Query:");
                Console.WriteLine(q.ToAlgebra().ToQuery().ToString());
                Console.WriteLine();
                Console.WriteLine();
            }
        }
Example #10
0
        public void SparqlBind()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT ?triple WHERE { ?s ?p ?o . BIND(fn:concat(STR(?s), ' ', STR(?p), ' ', STR(?o)) AS ?triple) }";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count > 0, "Expected 1 or more results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
 static object Execute(TripleStore store, string sparql)
 {
     InMemoryDataset ds = new InMemoryDataset(store);
     ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);
     SparqlQueryParser sparqlparser = new SparqlQueryParser();
     SparqlQuery query = sparqlparser.ParseFromString(sparql);
     return processor.ProcessQuery(query);
 }
Example #12
0
        /// <summary>
        /// Creates a new SPARQL View
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="store">Triple Store to query</param>
        public BaseSparqlView(String sparqlQuery, ITripleStore store)
        {
            SparqlQueryParser parser = new SparqlQueryParser();
            this._q = parser.ParseFromString(sparqlQuery);
            this._store = store;

            this._async = new UpdateViewDelegate(this.UpdateViewInternal);
            this.Initialise();
        }
 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);
 }
Example #14
0
 public static SparqlQuery ParseSparql(string exp)
 {
     var parser = new SparqlQueryParser(SparqlQuerySyntax.Extended);
     var expressionFactories = parser.ExpressionFactories.ToList();
     expressionFactories.Add(new BrightstarFunctionFactory());
     parser.ExpressionFactories = expressionFactories;
     var query = parser.ParseFromString(exp);
     return query;
 }
        public void SparqlResultSetToDataTable2()
        {
            String query = "PREFIX ex: <http://example.org/vehicles/> SELECT * WHERE {?s a ex:Car . OPTIONAL { ?s ex:Speed ?speed }}";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");

            Object results = g.ExecuteQuery(q);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;

                DataTable table = new DataTable();
                foreach (String var in rset.Variables)
                {
                    table.Columns.Add(new DataColumn(var, typeof(INode)));
                }

                foreach (SparqlResult r in rset)
                {
                    DataRow row = table.NewRow();

                    foreach (String var in rset.Variables)
                    {
                        if (r.HasValue(var))
                        {
                            row[var] = r[var];
                        }
                        else
                        {
                            row[var] = null;
                        }
                    }
                    table.Rows.Add(row);
                }

                Assert.AreEqual(rset.Variables.Count(), table.Columns.Count, "Number of Columns should be equal");
                Assert.AreEqual(rset.Count, table.Rows.Count, "Number of Rows should be equal");

                foreach (DataRow row in table.Rows)
                {
                    foreach (DataColumn col in table.Columns)
                    {
                        Object temp = row[col];
                        Console.Write(col.ColumnName + " = " + ((temp != null) ? temp.ToString() : String.Empty) + " , ");
                    }
                    Console.WriteLine();
                }
            }
            else
            {
                Assert.Fail("Query should have returned a Result Set");
            }
        }
 /// <summary>
 /// Determines the type of model that will be returned by the specified SPARQL query
 /// </summary>
 /// <param name="sparqlQuery"></param>
 /// <returns></returns>
 /// <exception cref="ArgumentNullException">raised if <paramref name="sparqlQuery"/> is NULL</exception>
 /// <exception cref="ArgumentException">rasised if <paramref name="sparqlQuery"/> is an empty string</exception>
 /// <exception cref="VDS.RDF.Parsing.RdfParseException">raised if the sparql query could not be parsed</exception>
 public static SerializableModel GetResultModel(string sparqlQuery)
 {
     if (sparqlQuery == null) throw new ArgumentNullException("sparqlQuery", Strings.BrightstarServiceClient_QueryMustNotBeNull);
     if (String.IsNullOrEmpty(sparqlQuery)) throw new ArgumentException(Strings.BrightstarServiceClient_QueryMustNotBeEmptyString, "sparqlQuery");
     var p = new SparqlQueryParser();
     var q = p.ParseFromString(sparqlQuery);
     switch (q.QueryType)
     {
         case SparqlQueryType.Construct:
         case SparqlQueryType.Describe:
         case SparqlQueryType.DescribeAll:
             return SerializableModel.RdfGraph;
         default:
             return SerializableModel.SparqlResultSet;
     }
 }
        public void SparqlParsingNestedGraphPatternFirstItem2()
        {
            try
            {
                SparqlQueryParser parser = new SparqlQueryParser();
                SparqlQuery q = parser.ParseFromFile("childgraphpattern2.rq");

                Console.WriteLine(q.ToString());
                Console.WriteLine();
                Console.WriteLine(q.ToAlgebra().ToString());
            }
            catch (RdfParseException parseEx)
            {
                TestTools.ReportError("Parsing Error", parseEx, true);
            }
        }
 private static SparqlQuery ParseSparql(string exp)
 {
     var parser = new SparqlQueryParser(SparqlQuerySyntax.Extended);
     var expressionFactories = parser.ExpressionFactories.ToList();
     expressionFactories.Add(new BrightstarFunctionFactory());
     parser.ExpressionFactories = expressionFactories;
     lock (SparqlParserLock)
     {
         // Lock is required because dotNetRDF currently has
         // a contention issue in its Trie implementation
         // This may be fixed in 0.7.1
         // TODO: Check if this is needed when we upgrade to 0.7.x
         var query = parser.ParseFromString(exp);
         return query;
     }
 }
Example #19
0
        public void SparqlServiceUsingDBPediaAndBindings()
        {
            String query = "SELECT * WHERE { SERVICE <http://dbpedia.org/sparql> { ?s a ?type } } BINDINGS ?s { ( <http://dbpedia.org/resource/Southampton> ) ( <http://dbpedia.org/resource/Ilkeston> ) }";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(new TripleStore());
            Object results = processor.ProcessQuery(q);
            if (results is SparqlResultSet)
            {
                TestTools.ShowResults(results);
            }
            else
            {
                Assert.Fail("Should have returned a SPARQL Result Set");
            }
        }
Example #20
0
        public void SparqlServiceWithNonExistentService()
        {
            String query = "SELECT * WHERE { SERVICE <http://www.dotnetrdf.org/noSuchService> { ?s a ?type } } LIMIT 10";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(new TripleStore());
            try
            {
                Object results = processor.ProcessQuery(q);
                Assert.Fail("Should have errored");
            }
            catch (RdfQueryException queryEx)
            {
                Console.WriteLine("Errored as expected");
                TestTools.ReportError("Query Error", queryEx, false);
            }
        }
 public IEnumerable<IDataObject> BindRdfDataObjects(IGraph g,
                                                    IList<OrderingDirection> orderingDirections)
 {
     var p = new LeviathanQueryProcessor(new InMemoryDataset(g));
     var queryString = MakeOrderedResourceQuery(orderingDirections);
     var sparqlParser = new SparqlQueryParser();
     var query = sparqlParser.ParseFromString(queryString);
     var queryResultSet = p.ProcessQuery(query) as SparqlResultSet;
     if (queryResultSet != null)
     {
         foreach (var row in queryResultSet.Results)
         {
             INode uriNode;
             if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode)
             {
                 yield return BindRdfDataObject((IUriNode) uriNode, g);
             }
         }
     }
 } 
Example #22
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;
                }
            }
        }
        public void SparqlParsingSubQueryWithLimitAndOrderBy()
        {
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");

            String query = "SELECT * WHERE { { SELECT * WHERE {?s ?p ?o} ORDER BY ?p ?o LIMIT 2 } }";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Object results = g.ExecuteQuery(q);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                TestTools.ShowResults(rset);

                Assert.IsTrue(rset.All(r => r.HasValue("s") && r.HasValue("p") && r.HasValue("o")), "All Results should have had ?s, ?p and ?o variables");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
 public Stream ExecuteQuery(string queryExpression, IList<string> datasetGraphUris)
 {
     var parser = new SparqlQueryParser();
     var query = parser.ParseFromString(queryExpression);
     var sparqlResults = _queryProcessor.ProcessQuery(query);
     var memoryStream = new MemoryStream();
     using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8))
     {
         if (sparqlResults is SparqlResultSet)
         {
             var resultSet = sparqlResults as SparqlResultSet;
             var writer = new SparqlXmlWriter();
             writer.Save(resultSet, streamWriter);
         }
         else if (sparqlResults is IGraph)
         {
             var g = sparqlResults as IGraph;
             var writer = new RdfXmlWriter();
             writer.Save(g, streamWriter);
         }
     }
     return new MemoryStream(memoryStream.ToArray());
     //return new MemoryStream(Encoding.UTF8.GetBytes(buff.ToString()), false);
 }
        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 SparqlFilterOptionalNotBound()
        {
            Graph g = new Graph();
            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");

            SparqlParameterizedString query = new SparqlParameterizedString();
            query.Namespaces.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));
            query.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS));
            query.CommandText = "SELECT * WHERE { ?property a rdf:Property . OPTIONAL { ?property rdfs:range ?range } FILTER (!BOUND(?range)) }";

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);
            SparqlResultSet results = g.ExecuteQuery(q) as SparqlResultSet;
            if (results != null)
            {
                TestTools.ShowResults(results);

                Assert.IsTrue(results.All(r => !r.HasValue("range") || r["range"] == null), "There should be no values for ?range returned");
            }
            else
            {
                Assert.Fail("Did not get a SparqlResultSet as expected");
            }
        }
Example #27
0
        /// <summary>
        /// Attempt to auto-detect the syntax of the current document using the filename as a guide
        /// </summary>
        public void AutoDetectSyntax(String filename)
        {
            if (this._editor == null) return; //Not yet ready

            if (filename == null || System.IO.Path.GetExtension(filename).Equals(String.Empty))
            {
                try
                {
                    //First see if it's an RDF format
                    IRdfReader parser = StringParser.GetParser(this._editor.Text);

                    if (parser is NTriplesParser)
                    {
                        //NTriples is the fallback so if we get this check if it's actually SPARQL Results
                        try
                        {
                            ISparqlResultsReader sparqlParser = StringParser.GetResultSetParser(this._editor.Text);
                        }
                        catch (RdfParserSelectionException)
                        {
                            //Not a valid SPARQL Results format - may be a SPARQL Query or a SPARQL Update?
                            SparqlQueryParser queryParser = new SparqlQueryParser(SparqlQuerySyntax.Sparql_1_1);
                            try
                            {
                                SparqlQuery q = queryParser.ParseFromString(this._editor.Text);
                                this.SetHighlighter("SparqlQuery11");
                            }
                            catch (RdfParseException)
                            {
                                //Not a valid SPARQL Query - valid SPARQL Update?
                                SparqlUpdateParser updateParser = new SparqlUpdateParser();
                                try
                                {
                                    SparqlUpdateCommandSet cmds = updateParser.ParseFromString(this._editor.Text);
                                    this.SetHighlighter("SparqlUpdate11");
                                }
                                catch (RdfParseException)
                                {
                                    //Was probably actually NTriples
                                    this.SetHighlighter(parser);
                                }
                            }
                        }
                    }
                    else
                    {
                        //Got a non NTriples RDF parser so use that to set Highlighter
                        this.SetHighlighter(parser);
                    }
                }
                catch (RdfParserSelectionException)
                {
                    this.SetNoHighlighting();
                }
                return;
            }

            try
            {
                IHighlightingDefinition def = HighlightingManager.Instance.GetDefinitionByExtension(System.IO.Path.GetExtension(filename));
                if (this._enableHighlighting) this._editor.SyntaxHighlighting = def;

                if (def != null)
                {
                    this._currSyntax = def.Name;
                    this.SetCurrentHighlighterChecked(def.Name);
                    this.SetCurrentValidator(def.Name);
                    this.SetCurrentAutoCompleter(def.Name);
                }
                else
                {
                    this.SetNoHighlighting();
                }
            }
            catch
            {
                this.SetNoHighlighting();
            }
        }
        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 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);
                }
            }
        }
Example #30
0
        /// <summary>
        /// Executes a SPARQL Query on the Triple Store processing the results with an appropriate handler from those provided
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        /// <param name="query">SPARQL Query as unparsed String</param>
        public virtual void ExecuteQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String query)
        {
            //Parse the Query
            SparqlQueryParser sparqlparser = new SparqlQueryParser();
            SparqlQuery q = sparqlparser.ParseFromString(query);

            //Invoke other execute method
            this.ExecuteQuery(rdfHandler, resultsHandler, q);
        }