コード例 #1
0
        public void SparqlGroupByAssignmentSimple2()
        {
            String            query  = "SELECT ?x (COUNT(?p) AS ?predicates) WHERE { ?s ?p ?o } GROUP BY ?s AS ?x";
            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, "resources\\InferenceTest.ttl");

            Object results = g.ExecuteQuery(q);

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

                Assert.True(rset.All(r => r.HasValue("x") && !r.HasValue("s") && r.HasValue("predicates")), "All Results should have a ?x and ?predicates variables and no ?s variable");
            }
            else
            {
                Assert.True(false, "Didn't get a Result Set as expected");
            }
        }
コード例 #2
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");
            }
        }
コード例 #3
0
        public void SparqlGroupByAssignmentExpression3()
        {
            String            query  = "SELECT ?lang (SAMPLE(?o) AS ?example) WHERE { ?s ?p ?o . FILTER(ISLITERAL(?o)) } GROUP BY (LANG(?o) AS ?lang) HAVING LANGMATCHES(?lang, \"*\")";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);

            SparqlFormatter formatter = new SparqlFormatter();

            Console.WriteLine(formatter.Format(q));
            Console.WriteLine();

            QueryableGraph g = new QueryableGraph();

            UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Southampton"));

            Object results = g.ExecuteQuery(q);

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

                Assert.IsTrue(rset.All(r => r.HasValue("lang") && r.HasValue("example")), "All Results should have a ?lang and a ?example variable");
            }
            else
            {
                Assert.Fail("Didn't get a Result Set as expected");
            }
        }
コード例 #4
0
        public void SparqlFunctionsNow()
        {
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromFile("resources\\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();
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store);
            SparqlResultSet         results   = processor.ProcessQuery(q) as SparqlResultSet;

            if (results != null)
            {
                Assert.IsTrue(results.Result, "Result should be true");
            }
            else
            {
                Assert.Fail("Expected a non-null result");
            }
        }
コード例 #5
0
        public void SparqlFormattingOptionalAtRoot()
        {
            SparqlQuery q = new SparqlQuery {
                QueryType = SparqlQueryType.Select
            };

            q.AddVariable(new SparqlVariable("s", true));

            GraphPattern gp = new GraphPattern();

            gp.IsOptional = true;
            gp.AddTriplePattern(new TriplePattern(new VariablePattern("s"), new VariablePattern("p"), new VariablePattern("o")));
            q.RootGraphPattern = gp;

            String toStr = q.ToString();

            Console.WriteLine("ToString() Form:");
            Console.WriteLine(toStr);
            Assert.AreEqual(2, toStr.ToCharArray().Where(c => c == '{').Count());
            Assert.AreEqual(2, toStr.ToCharArray().Where(c => c == '}').Count());
            Console.WriteLine();

            SparqlFormatter formatter = new SparqlFormatter();
            String          fmtStr    = formatter.Format(q);

            Console.WriteLine("SparqlFormatter Form:");
            Console.WriteLine(fmtStr);
            Assert.AreEqual(2, fmtStr.ToCharArray().Where(c => c == '{').Count());
            Assert.AreEqual(2, fmtStr.ToCharArray().Where(c => c == '}').Count());
        }
コード例 #6
0
        public void SparqlGroupByAssignmentExpression3()
        {
            if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing))
            {
                throw new SkipTestException("Test Config marks Remote Parsing as unavailable, test cannot be run");
            }

            String            query  = "SELECT ?lang (SAMPLE(?o) AS ?example) WHERE { ?s ?p ?o . FILTER(ISLITERAL(?o)) } GROUP BY (LANG(?o) AS ?lang) HAVING LANGMATCHES(?lang, \"*\")";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);

            SparqlFormatter formatter = new SparqlFormatter();

            Console.WriteLine(formatter.Format(q));
            Console.WriteLine();

            QueryableGraph g = new QueryableGraph();

            UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Southampton"));

            Object results = g.ExecuteQuery(q);

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

                Assert.True(rset.All(r => r.HasValue("lang") && r.HasValue("example")), "All Results should have a ?lang and a ?example variable");
            }
            else
            {
                Assert.True(false, "Didn't get a Result Set as expected");
            }
        }
コード例 #7
0
        private static void SetUris(SparqlParameterizedString sparqlParameterizedString, string parameter, IEnumerable <Uri> values)
        {
            // Enclose Uris in <>
            var formatter = new SparqlFormatter();
            var factory   = new NodeFactory();

            sparqlParameterizedString.CommandText = sparqlParameterizedString.CommandText.Replace($"@{parameter}", string.Join(" ", values.Select(uri => formatter.Format(factory.CreateUriNode(uri)))));
        }
コード例 #8
0
        private static void SetLiterals(SparqlParameterizedString sparqlParameterizedString, string parameter, IEnumerable <string> values)
        {
            // Create literal nodes
            var formatter = new SparqlFormatter();
            var factory   = new NodeFactory();

            sparqlParameterizedString.CommandText = sparqlParameterizedString.CommandText.Replace($"@{parameter}", string.Join(" ", values.Select(value => formatter.Format(factory.CreateLiteralNode(value)))));
        }
コード例 #9
0
        private void RunTest(IFullTextIndexer indexer, String query, IEnumerable <INode> expected)
        {
            this.EnsureTestData();

            indexer.Index(this._dataset);
            indexer.Dispose();

            //Build the SPARQL Query and parse it
            SparqlParameterizedString queryString = new SparqlParameterizedString(query);

            queryString.Namespaces = this.GetQueryNamespaces();
            SparqlQuery q = this._parser.ParseFromString(queryString);

            SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap);

            Console.WriteLine("Parsed Query:");
            Console.WriteLine(formatter.Format(q));

            Console.WriteLine("Expected Results:");
            foreach (INode n in expected)
            {
                Console.WriteLine(n.ToString(formatter));
            }
            Console.WriteLine();

            LuceneSearchProvider provider = new LuceneSearchProvider(LuceneTestHarness.LuceneVersion, LuceneTestHarness.Index);

            try
            {
                q.AlgebraOptimisers = new IAlgebraOptimiser[] { new FullTextOptimiser(provider) };

                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(this._dataset);
                SparqlResultSet         results   = processor.ProcessQuery(q) as SparqlResultSet;
                if (results != null)
                {
                    TestTools.ShowResults(results);

                    foreach (INode n in expected)
                    {
                        Assert.IsTrue(results.Any(r => r.HasValue("match") && r["match"] != null && r["match"].Equals(n)), "Did not get expected ?match => " + formatter.Format(n));
                    }
                    foreach (SparqlResult r in results)
                    {
                        Assert.IsTrue(r.HasValue("match") && r["match"] != null && expected.Contains(r["match"]), "Unexpected Match " + formatter.Format(r["match"]));
                    }
                }
                else
                {
                    Assert.Fail("Did not get a SPARQL Result Set as expected");
                }
            }
            finally
            {
                provider.Dispose();
                LuceneTestHarness.Index.Dispose();
            }
        }
コード例 #10
0
        private void RunTest(IFullTextIndexer indexer, String query, int expectedResults, bool exact)
        {
            this.EnsureTestData();

            indexer.Index(this._dataset);
            indexer.Dispose();

            //Build the SPARQL Query and parse it
            SparqlParameterizedString queryString = new SparqlParameterizedString(query);

            queryString.Namespaces = this.GetQueryNamespaces();
            SparqlQuery q = this._parser.ParseFromString(queryString);

            SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap);

            Console.WriteLine("Parsed Query:");
            Console.WriteLine(formatter.Format(q));

            LuceneSearchProvider            provider = new LuceneSearchProvider(LuceneTestHarness.LuceneVersion, LuceneTestHarness.Index);
            FullTextPropertyFunctionFactory factory  = new FullTextPropertyFunctionFactory();

            try
            {
                PropertyFunctionFactory.AddFactory(factory);
                q.AlgebraOptimisers         = new IAlgebraOptimiser[] { new FullTextOptimiser(provider) };
                Options.AlgebraOptimisation = true;

                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(this._dataset);
                SparqlResultSet         results   = processor.ProcessQuery(q) as SparqlResultSet;
                if (results != null)
                {
                    TestTools.ShowResults(results);

                    if (exact)
                    {
                        Assert.Equal(expectedResults, results.Count);
                    }
                    else
                    {
                        Assert.True(expectedResults >= results.Count, "Got more results that the expected maximum");
                    }
                }
                else
                {
                    Assert.True(false, "Did not get a SPARQL Result Set as expected");
                }
            }
            finally
            {
                PropertyFunctionFactory.RemoveFactory(factory);
                provider.Dispose();
                LuceneTestHarness.Index.Dispose();
            }
        }
コード例 #11
0
 private void ShowQueryInformation(QueryTask task)
 {
     if (task.Query != null)
     {
         SparqlFormatter formatter = new SparqlFormatter(task.Query.NamespaceMap);
         StringWriter    writer    = new StringWriter();
         writer.WriteLine("Parsed Query:");
         writer.WriteLine(formatter.Format(task.Query));
         writer.WriteLine("SPARQL Algebra:");
         writer.WriteLine(task.Query.ToAlgebra().ToString());
         CrossThreadSetText(this.txtAdvInfo, writer.ToString());
     }
 }
コード例 #12
0
        public void SparqlParsingCore427_2()
        {
            const string query = "SELECT (StrUUID() AS ?test) { }";

            var q = this._parser.ParseFromString(query);

            var toString = q.ToString();

            Assert.Contains("(STRUUID", toString);

            var formattedString = new SparqlFormatter().Format(q);

            Assert.Contains("(STRUUID", formattedString);
        }
コード例 #13
0
ファイル: ParsingTests.cs プロジェクト: yuryk53/dotnetrdf
        public void SparqlParsingCore427_2()
        {
            const String query = "SELECT (StrUUID() AS ?test) { }";

            SparqlQuery q = this._parser.ParseFromString(query);

            String toString = q.ToString();

            Assert.IsTrue(toString.Contains("(STRUUID"));

            String formattedString = new SparqlFormatter().Format(q);

            Assert.IsTrue(formattedString.Contains("(STRUUID"));
        }
コード例 #14
0
        public void SparqlParsingCore427_1()
        {
            const String query = "SELECT (UUID() AS ?test) { }";

            SparqlQuery q = this._parser.ParseFromString(query);

            String toString = q.ToString();

            Assert.Contains("(UUID", toString);

            String formattedString = new SparqlFormatter().Format(q);

            Assert.Contains("(UUID", formattedString);
        }
コード例 #15
0
        public void SparqlParsingSubqueries4()
        {
            String            query  = "SELECT * WHERE { { SELECT * WHERE { ?s ?p ?o } } }";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);

            Console.WriteLine("Parsed original input OK");

            SparqlFormatter formatter = new SparqlFormatter();
            String          query2    = formatter.Format(q);
            SparqlQuery     q2        = parser.ParseFromString(query2);

            Console.WriteLine("Parsed reserialized input OK");
        }
コード例 #16
0
        private static string SetUris(string sparql, IEnumerable <string> ids)
        {
            var formatter = new SparqlFormatter();
            var factory   = new NodeFactory();

            string format(string id)
            {
                var uri  = new Uri(Program.BaseUri, id);
                var node = factory.CreateUriNode(uri);

                return(formatter.Format(node));
            }

            return(sparql.Replace("@concepts", string.Join(" ", ids.Select(format))));
        }
コード例 #17
0
        public void SparqlParsingConstructShortForm()
        {
            List <String> valid = new List <string>()
            {
                "CONSTRUCT WHERE {?s ?p ?o }",
                "CONSTRUCT WHERE {?s a ?type }",
            };

            List <String> invalid = new List <string>()
            {
                "CONSTRUCT {?s ?p ?o}",
                "CONSTRUCT WHERE { ?s ?p ?o . FILTER(ISLITERAL(?o)) }",
                "CONSTRUCT WHERE { GRAPH ?g { ?s ?p ?o } }",
                "CONSTRUCT WHERE { ?s ?p ?o . OPTIONAL {?s a ?type}}",
                "CONSTRUCT WHERE { ?s a ?type . BIND (<http://example.org> AS ?thing) }",
                "CONSTRUCT WHERE { {SELECT * WHERE { ?s ?p ?o } } }"
            };

            SparqlQueryParser parser    = new SparqlQueryParser();
            SparqlFormatter   formatter = new SparqlFormatter();

            foreach (String v in valid)
            {
                Console.WriteLine("Valid Input: " + v);
                SparqlQuery q = parser.ParseFromString(v);
                Console.WriteLine(formatter.Format(q));
                Console.WriteLine();
            }

            foreach (String iv in invalid)
            {
                Console.WriteLine("Invalid Input: " + iv);
                try
                {
                    SparqlQuery q = parser.ParseFromString(iv);
                    Assert.Fail("Should have thrown a Parsing Error");
                }
                catch (RdfParseException parseEx)
                {
                    Console.WriteLine("Errored as expected");
                    TestTools.ReportError("Parsing Error", parseEx);
                }
                Console.WriteLine();
            }
        }
コード例 #18
0
        private void TestExtractPatterns(String query, int expectedPatterns, int expectedSubjArgs, int expectedObjArgs)
        {
            FullTextPropertyFunctionFactory factory = new FullTextPropertyFunctionFactory();

            try
            {
                PropertyFunctionFactory.AddFactory(factory);

                SparqlParameterizedString queryString = new SparqlParameterizedString(query);
                queryString.Namespaces.AddNamespace("pf", new Uri(FullTextHelper.FullTextMatchNamespace));
                SparqlQuery     q         = this._parser.ParseFromString(queryString);
                SparqlFormatter formatter = new SparqlFormatter(queryString.Namespaces);

                Console.WriteLine(formatter.Format(q));
                Console.WriteLine();

                List <IPropertyFunctionPattern> ps = PropertyFunctionHelper.ExtractPatterns(q.RootGraphPattern.TriplePatterns);
                Console.WriteLine(ps.Count + " Pattern(s) extracted");
                foreach (IPropertyFunctionPattern propFunc in ps.Where(p => p.PropertyFunction is FullTextMatchPropertyFunction))
                {
                    Console.WriteLine("Match Variable: " + propFunc.SubjectArgs.First().ToString());
                    Console.WriteLine("Score Variable: " + (propFunc.SubjectArgs.Count() > 1 ? propFunc.SubjectArgs.Skip(1).First().ToString() : "N/A"));
                    Console.WriteLine("Search Term: " + propFunc.ObjectArgs.First().ToString());
                    Console.WriteLine("Threshold/Limit: " + (propFunc.ObjectArgs.Count() > 1 ? propFunc.ObjectArgs.Skip(1).First().ToString() : "N/A"));
                    Console.WriteLine("Limit: " + (propFunc.ObjectArgs.Count() > 2 ? propFunc.ObjectArgs.Skip(2).First().ToString() : "N/A"));
                    Console.WriteLine();

                    if (expectedSubjArgs > 0)
                    {
                        Assert.Equal(expectedSubjArgs, propFunc.SubjectArgs.Count());
                    }
                    if (expectedObjArgs > 0)
                    {
                        Assert.Equal(expectedObjArgs, propFunc.ObjectArgs.Count());
                    }
                }

                Assert.Equal(expectedPatterns, ps.Count);
            }
            finally
            {
                PropertyFunctionFactory.RemoveFactory(factory);
            }
        }
コード例 #19
0
        public XsdtTypeConverter()
        {
            this._formatter = new SparqlFormatter(this._g);

            typeLookup.Add(XsdtPrimitiveDataType.XsdtString, typeof(string));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtBoolean, typeof(Boolean));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtFloat, typeof(Single));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtDouble, typeof(Double));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtDecimal, typeof(Decimal));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtDuration, typeof(TimeSpan));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtDayTimeDuration, typeof(TimeSpan));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtShort, typeof(Int16));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtInt, typeof(Int32));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtLong, typeof(Int64));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtHexBinary, typeof(Byte[]));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtAnyUri, typeof(Uri));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtDateTime, typeof(DateTime));
            typeLookup.Add(XsdtPrimitiveDataType.XsdtDate, typeof(DateTime));
        }
コード例 #20
0
        private static string addProvenance(IEnumerable <Triple> additions, IEnumerable <Triple> removals)
        {
            Graph           graph           = new Graph();
            StringBuilder   sb              = new StringBuilder();
            SparqlFormatter sparqlFormatter = new SparqlFormatter();
            DateTimeOffset  dt              = DateTimeOffset.UtcNow;

            sb.AppendLine(";INSERT DATA {");
            foreach (Triple removed in removals)
            {
                sb.Append($@"[] <http://example.com/subject> {sparqlFormatter.Format(removed.Subject)};
                        <http://example.com/predicate> {sparqlFormatter.Format(removed.Predicate)};
                        <http://example.com/dateTime> {sparqlFormatter.Format(dt.ToLiteral(graph))};
                        <http://example.com/oldObject> {sparqlFormatter.Format(removed.Object)}");
                IEnumerable <Triple> foundAdded = additions.Where(a => a.HasSubject(removed.Subject) && a.HasPredicate(removed.Predicate));
                if (foundAdded.Any())
                {
                    sb.AppendLine(";");
                    foreach (Triple added in foundAdded)
                    {
                        sb.AppendLine($@"<http://example.com/newObject> {sparqlFormatter.Format(added.Object)}.");
                    }
                }
                else
                {
                    sb.AppendLine($@".");
                }
            }
            foreach (Triple added in additions)
            {
                if (removals.Any(a => a.HasSubject(added.Subject) && a.HasPredicate(added.Predicate)) == false)
                {
                    sb.Append($@"[] <http://example.com/subject> {sparqlFormatter.Format(added.Subject)};
                        <http://example.com/predicate> {sparqlFormatter.Format(added.Predicate)};
                        <http://example.com/dateTime> {sparqlFormatter.Format(dt.ToLiteral(graph))};
                        <http://example.com/newObject> {sparqlFormatter.Format(added.Object)}.");
                }
            }
            sb.AppendLine("}");

            return(sb.ToString());
        }
コード例 #21
0
        public void SparqlGroupByRefactor7()
        {
            String query = "SELECT ?s WHERE { ?s ?p ?o } GROUP BY (?s)";

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

            String queryStr = q.ToString();

            Console.WriteLine("Raw ToString()");
            Console.WriteLine(queryStr);
            Console.WriteLine();
            Assert.Contains("GROUP BY ?s", queryStr);

            String queryStrFmt = new SparqlFormatter().Format(q);

            Console.WriteLine("Formatted String");
            Console.WriteLine(queryStrFmt);
            Assert.Contains("GROUP BY ?s", queryStrFmt);
        }
コード例 #22
0
 private void ShowQueryInformation(QueryTask task)
 {
     CrossThreadSetEnabled(this.btnViewResults, task.State == TaskState.Completed && task.Result != null);
     if (task.Query != null)
     {
         StringWriter writer = new StringWriter();
         writer.WriteLine("Parsed Query:");
         if (task.Query != null)
         {
             SparqlFormatter formatter = new SparqlFormatter(task.Query.NamespaceMap);
             writer.WriteLine(formatter.Format(task.Query));
             writer.WriteLine("SPARQL Algebra:");
             writer.WriteLine(task.Query.ToAlgebra().ToString());
         }
         else
         {
             writer.WriteLine("Unavailable - Not standard SPARQL 1.0/1.1");
         }
         CrossThreadSetText(this.txtAdvInfo, writer.ToString());
     }
 }
コード例 #23
0
        private static void SetUris(SparqlParameterizedString query, string name, string value, Uri baseUri)
        {
            var formatter = new SparqlFormatter();
            var factory   = new NodeFactory();

            Func <string, string> format = instanceId =>
            {
                var uri  = new Uri(baseUri, instanceId);
                var node = factory.CreateUriNode(uri);

                return(formatter.Format(node));
            };

            var formattedUris = value.Split(',').Select(format);

            value = string.Join(" ", formattedUris);

            var parameter = $"@{name}";

            query.CommandText = query.CommandText.Replace(parameter, value);
        }
コード例 #24
0
        public void SparqlBlankNodeVariables1()
        {
            this.EnsureTestData();

            SparqlQuery q = this._parser.ParseFromString("SELECT ?o WHERE { _:s ?p1 ?o1 FILTER(ISURI(?o1)) ?o1 ?p2 ?o . FILTER(ISLITERAL(?o)) }");

            q.AlgebraOptimisers = new IAlgebraOptimiser[] { new StrictAlgebraOptimiser() };
            SparqlFormatter formatter = new SparqlFormatter();

            Console.WriteLine(formatter.Format(q));
            Console.WriteLine(q.ToAlgebra().ToString());

            SparqlResultSet results = this._processor.ProcessQuery(q) as SparqlResultSet;

            if (results == null)
            {
                Assert.True(false, "Did not get a SPARQL Result Set as expected");
            }
            Assert.False(results.Count == 0, "Result Set should not be empty");

            Assert.True(results.All(r => r.HasValue("o") && r["o"] != null && r["o"].NodeType == NodeType.Literal), "All results should be literals");
        }
コード例 #25
0
        public void SparqlParsingDescribeHangingWhere()
        {
            List <String> valid = new List <string>()
            {
                "DESCRIBE ?s WHERE { ?s a ?type }",
                "DESCRIBE <http://example.org/>",
                "PREFIX ex: <http://example.org/> DESCRIBE ex:"
            };

            List <String> invalid = new List <string>()
            {
                "DESCRIBE ?s WHERE"
            };

            SparqlQueryParser parser    = new SparqlQueryParser();
            SparqlFormatter   formatter = new SparqlFormatter();

            foreach (String v in valid)
            {
                SparqlQuery q = parser.ParseFromString(v);
                Console.WriteLine(formatter.Format(q));
                Console.WriteLine();
            }

            foreach (String iv in invalid)
            {
                try
                {
                    SparqlQuery q = parser.ParseFromString(iv);
                    Assert.Fail("Should have thrown a Parsing Error");
                }
                catch (RdfParseException parseEx)
                {
                    Console.WriteLine("Errored as expected");
                    TestTools.ReportError("Parsing Error", parseEx);
                }
            }
        }
コード例 #26
0
        static void loadOwl(string ruta)
        {
            //string path = Application.StartupPath.ToString() + "\\JudoOntology.owl";
            // string path = Application.StartupPath.ToString() + "\\JudoOntology.owl";
            string path = Application.StartupPath.ToString() + "\\FoodOntologyRecomender.owl";
            IGraph g    = new Graph();

            g.LoadFromFile(path, new RdfXmlParser());
            try
            {
                /*foreach (IUriNode u in g.Nodes.UriNodes())
                 * {
                 *    //Write the URI to the Console
                 *    Console.WriteLine(u.Uri.ToString());
                 * }
                 *
                 *
                 * Console.WriteLine(g.BaseUri);foreach (Triple u in g.Triples)
                 * {
                 *    //Write the URI to the Console
                 *    Console.WriteLine(u.ToString());
                 * }*/


                //Fill in the code shown on this page here to build your hello world application

                /*
                 * IUriNode dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
                 * IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
                 * ILiteralNode helloWorld = g.CreateLiteralNode("Hello World");
                 * ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");
                 *
                 * g.Assert(new Triple(dotNetRDF, says, helloWorld));
                 * g.Assert(new Triple(dotNetRDF, says, bonjourMonde));
                 *
                 * Console.WriteLine();
                 * Console.WriteLine("Raw Output");
                 * Console.WriteLine();*/

                /*
                 * foreach (Triple t in g.Triples)
                 * {
                 *
                 *  Console.WriteLine(t.ToString());
                 * }
                 * foreach (IUriNode u in g.Nodes.UriNodes())
                 * {
                 *  //Write the URI to the Console
                 *  Console.WriteLine(u.Uri.ToString());
                 * }*/

                //Create a Parameterized String
                SparqlParameterizedString queryString = new SparqlParameterizedString();

                //Add a namespace declaration
                queryString.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
                queryString.Namespaces.AddNamespace("owl", new Uri("http://www.w3.org/2002/07/owl#"));
                queryString.Namespaces.AddNamespace("xsd", new Uri("http://www.w3.org/2001/XMLSchema#"));
                queryString.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#"));
                //Set the SPARQL command
                //For more complex queries we can do this in multiple lines by using += on the
                //CommandText property
                //Note we can use @name style parameters here

                //      queryString.CommandText = "SELECT * WHERE { ?s ex:property @value }";

                /*
                 * queryString.CommandText = "SELECT ?individual ?class WHERE {?individual"+
                 *  " rdf:type owl:NamedIndividual. "+
                 *  "?class rdf:type owl:Class.}";*/
                /*
                 * // get all class in the model
                 * queryString.CommandText = "SELECT ?s WHERE { ?s rdf:type owl:Class } "; */



                //Inject a Value for the parameter
                // queryString.SetUri("value", new Uri("http://example.org/value"));
                //When we call ToString() we get the full command text with namespaces appended as PREFIX
                //declarations and any parameters replaced with their declared values

                Console.WriteLine(queryString.ToString());

                //We can turn this into a query by parsing it as in our previous example
                SparqlQueryParser parser = new SparqlQueryParser();
                SparqlQuery       query  = parser.ParseFromString(queryString);
                InMemoryDataset   ds     = new InMemoryDataset(g);
                //Get the Query processor
                ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);
                Object results = processor.ProcessQuery(query);
                if (results is SparqlResultSet)
                {
                    SparqlResultSet r = results as SparqlResultSet;

                    foreach (SparqlResult res in r)
                    {
                        SparqlFormatter format = new SparqlFormatter();
                        Console.WriteLine(res.ToString(format));
                    }
                }
            }
            catch (RdfParseException ex)
            {
                Console.WriteLine("Parser Error");
                Console.WriteLine(ex.Message);
            }
        }
コード例 #27
0
        public void RunQuery(String[] args)
        {
            //If we can't set options then we abort
            if (!this.SetOptions(args))
            {
                return;
            }

            if (this._query == null)
            {
                //Try to read query from Standard In instead
                this._query = Console.In.ReadToEnd();
                if (this._query.Equals(String.Empty))
                {
                    Console.Error.WriteLine("rdfQuery: No Query was specified");
                    return;
                }
            }

            //Parse the Query
            try
            {
                SparqlQuery q = this._parser.ParseFromString(this._query);

                //Set Timeout if necessary
                q.Timeout = this._timeout;
                q.PartialResultsOnTimeout = this._partialResults;

                //Execute the Query unless print was specified
                Object results = null;
                if (!this._print)
                {
                    switch (this._mode)
                    {
                    case RdfQueryMode.Local:
                        if (this._explain)
                        {
                            var processor = new ExplainQueryProcessor(this._store, this._level);
                            results = processor.ProcessQuery(q);
                        }
                        else
                        {
                            var processor = new LeviathanQueryProcessor(_store);
                            results = processor.ProcessQuery(q);
                        }
                        break;

                    case RdfQueryMode.Remote:
                        if (this._explain)
                        {
                            Console.Error.WriteLine("rdfQuery: Warning: Cannot explain queries when the query is being sent to a remote endpoint");
                        }
                        this._endpoint.Timeout = Convert.ToInt32(this._timeout);
                        switch (q.QueryType)
                        {
                        case SparqlQueryType.Construct:
                        case SparqlQueryType.Describe:
                        case SparqlQueryType.DescribeAll:
                            results = this._endpoint.QueryWithResultGraph(this._query);
                            break;

                        default:
                            results = this._endpoint.QueryWithResultSet(this._query);
                            break;
                        }
                        break;

                    case RdfQueryMode.Unknown:
                    default:
                        if (this._explain)
                        {
                            ExplainQueryProcessor processor = new ExplainQueryProcessor(new TripleStore(), this._level);
                            processor.ProcessQuery(q);
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfQuery: There were no inputs or a remote endpoint specified in the arguments so no query can be executed");
                        }
                        return;
                    }
                }

                //Select the Output Stream
                StreamWriter output;
                if (this._output == null)
                {
                    output = new StreamWriter(Console.OpenStandardOutput());
                }
                else
                {
                    output = new StreamWriter(this._output);
                }

                if (!this._print)
                {
                    //Output the Results
                    if (results is SparqlResultSet)
                    {
                        this._resultsWriter.Save((SparqlResultSet)results, output);
                    }
                    else if (results is IGraph)
                    {
                        this._graphWriter.Save((IGraph)results, output);
                    }
                    else
                    {
                        Console.Error.WriteLine("rdfQuery: The Query resulted in an unknown result");
                    }
                }
                else
                {
                    //If Printing Print the Query then the Algebra
                    SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap);
                    output.WriteLine("Query");
                    output.WriteLine(formatter.Format(q));
                    output.WriteLine();
                    output.WriteLine("Algebra");
                    output.WriteLine(q.ToAlgebra().ToString());
                    output.Flush();
                    output.Close();
                }
            }
            catch (RdfQueryTimeoutException timeout)
            {
                Console.Error.WriteLine("rdfQuery: Query Timeout: " + timeout.Message);
                if (this._debug)
                {
                    this.DebugErrors(timeout);
                }
                return;
            }
            catch (RdfQueryException queryEx)
            {
                Console.Error.WriteLine("rdfQuery: Query Error: " + queryEx.Message);
                if (this._debug)
                {
                    this.DebugErrors(queryEx);
                }
                return;
            }
            catch (RdfParseException parseEx)
            {
                Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message);
                if (this._debug)
                {
                    this.DebugErrors(parseEx);
                }
                return;
            }
            catch (RdfException rdfEx)
            {
                Console.Error.WriteLine("rdfQuery: RDF Error: " + rdfEx.Message);
                if (this._debug)
                {
                    this.DebugErrors(rdfEx);
                }
                return;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
                if (this._debug)
                {
                    this.DebugErrors(ex);
                }
                return;
            }
        }
コード例 #28
0
        private void LogStartQuery(SparqlQuery q)
        {
            SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap);

            this.Log("QUERY START", formatter.Format(q));
        }
コード例 #29
0
 /// <summary>
 /// Creates a new empty parameterized String
 /// </summary>
 public SparqlParameterizedString()
 {
     _formatter = new SparqlFormatter(_nsmap);
 }
コード例 #30
0
 public AsyncFusekiConnector(string updateUri)
 {
     this.updateUri  = updateUri;
     this.formatter  = new SparqlFormatter();
     this.httpClient = new HttpClient();
 }