Esempio n. 1
0
        public void SparqlQuery()
        {
            TripleStore store = new TripleStore();
            var         g     = new Graph();

            var parser = new NTriplesParser();

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

            store.Add(g);

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

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

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

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

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

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

                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result.ToString());
                }
            }
        }
Esempio n. 2
0
        public void SparqlGroupByComplex1()
        {
            String data  = @"PREFIX : <http://test/> INSERT DATA { :x :p 1 , 2 . :y :p 5 }";
            String query = @"SELECT ?s (CONCAT('$', STR(SUM(?o))) AS ?Total) WHERE { ?s ?p ?o } GROUP BY ?s";

            TripleStore store = new TripleStore();

            store.ExecuteUpdate(data);
            Assert.AreEqual(1, store.Graphs.Count);
            Assert.AreEqual(3, store.Triples.Count());

            //Aggregates may occur in project expressions and should evaluate correctly
            SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;

            Assert.IsNotNull(results);
            Assert.IsTrue(results.All(r => r.HasBoundValue("Total")));

            SparqlResult x = results.Where(r => ((IUriNode)r["s"]).Uri.Equals(new Uri("http://test/x"))).FirstOrDefault();

            Assert.IsNotNull(x);
            Assert.AreEqual("$3", x["Total"].AsValuedNode().AsString());

            SparqlResult y = results.Where(r => ((IUriNode)r["s"]).Uri.Equals(new Uri("http://test/y"))).FirstOrDefault();

            Assert.IsNotNull(y);
            Assert.AreEqual("$5", y["Total"].AsValuedNode().AsString());
        }
        public void SparqlPropertyPathEvaluationGraphInteraction()
        {
            String query = @"PREFIX ex: <http://www.example.org/schema#>
PREFIX in: <http://www.example.org/instance#>

SELECT ?x
FROM NAMED <http://example/1>
FROM NAMED <http://example/2>
WHERE
{
  GRAPH ?g { in:a ex:p1 / ex:p2 ?x . }
}";

            String data =
                @"<http://www.example.org/instance#a> <http://www.example.org/schema#p1> <http://www.example.org/instance#b> <http://example/1> .
<http://www.example.org/instance#b> <http://www.example.org/schema#p2> <http://www.example.org/instance#c> <http://example/2> .";

            TripleStore store = new TripleStore();

            store.LoadFromString(data, new NQuadsParser());

            SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;

            Assert.NotNull(results);
            Assert.Equal(SparqlResultsType.VariableBindings, results.ResultsType);
            Assert.Equal(0, results.Results.Count);
        }
Esempio n. 4
0
        public void SparqlGroupByRefactor4()
        {
            String query = @"PREFIX : <http://example/>

SELECT ?s ?w
FROM <http://group-data-2.ttl>
WHERE
{
  ?s :p ?v .
  OPTIONAL { ?s :q ?w . }
}
GROUP BY ?s ?w";

            String data = @"<http://example/s1> <http://example/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://group-data-2.ttl> .
<http://example/s3> <http://example/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://group-data-2.ttl> .
<http://example/s1> <http://example/q> ""9""^^<http://www.w3.org/2001/XMLSchema#integer> <http://group-data-2.ttl> .
<http://example/s2> <http://example/p> ""2""^^<http://www.w3.org/2001/XMLSchema#integer> <http://group-data-2.ttl> .";

            TripleStore store = new TripleStore();

            StringParser.ParseDataset(store, data, new NQuadsParser());

            SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;

            Assert.IsNotNull(results);
            TestTools.ShowResults(results);
            Assert.AreEqual(3, results.Count);
            Assert.AreEqual(2, results.Variables.Count());
            Assert.IsTrue(results.All(r => r.Count > 0), "One or more rows were empty");
            Assert.IsTrue(results.All(r => r.HasBoundValue("s")), "One or more rows were empty or failed to have a value for ?s");
        }
Esempio n. 5
0
        public void SparqlGroupByRefactor2()
        {
            String query = @"BASE <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/algebra/manifest#>
PREFIX : <http://example/>

SELECT * FROM <http://two-nested-opt.ttl>
WHERE 
{ 
  :x1 :p ?v . 
  OPTIONAL { 
    :x3 :q ?w . 
    OPTIONAL { :x2 :p ?v . } 
  }
}";

            String data = @"<http://example/x1> <http://example/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://two-nested-opt.ttl> .
<http://example/x2> <http://example/p> ""2""^^<http://www.w3.org/2001/XMLSchema#integer> <http://two-nested-opt.ttl> .
<http://example/x3> <http://example/q> ""3""^^<http://www.w3.org/2001/XMLSchema#integer> <http://two-nested-opt.ttl> .
<http://example/x3> <http://example/q> ""4""^^<http://www.w3.org/2001/XMLSchema#integer> <http://two-nested-opt.ttl> .";

            TripleStore store = new TripleStore();

            StringParser.ParseDataset(store, data, new NQuadsParser());

            SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;

            Assert.IsNotNull(results);
            TestTools.ShowResults(results);
            Assert.AreEqual(1, results.Count);
            Assert.AreEqual(2, results.Variables.Count());
        }
Esempio n. 6
0
        public void SparqlGroupByRefactor1()
        {
            String query = @"BASE <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/dataset/manifest#>
PREFIX : <http://example/>

SELECT * FROM <http://data-g3-dup.ttl>
FROM NAMED <http://data-g3.ttl>
WHERE 
{ 
  ?s ?p ?o . 
  GRAPH ?g { ?s ?q ?v . } 
}";

            String data = @"_:x <http://example/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-g3-dup.ttl> .
_:a <http://example/p> ""9""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-g3-dup.ttl> .
_:x <http://example/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-g3.ttl> .
_:a <http://example/p> ""9""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-g3.ttl> .";

            TripleStore store = new TripleStore();

            StringParser.ParseDataset(store, data, new NQuadsParser());

            SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;

            Assert.IsNotNull(results);
            TestTools.ShowResults(results);
            Assert.AreEqual(6, results.Variables.Count());
        }
Esempio n. 7
0
        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);
        }
        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);
        }
Esempio n. 9
0
        public void SparqlSimpleQuery1()
        {
            TripleStore store = new TripleStore();

            store.AddFromUri(new Uri("http://dbpedia.org/resource/Barack_Obama"));
            string            sparqlQuery  = "SELECT * WHERE {?s ?p ?o}";
            SparqlQueryParser sparqlParser = new SparqlQueryParser();
            SparqlQuery       query        = sparqlParser.ParseFromString(sparqlQuery);
            Object            results      = store.ExecuteQuery(query);
        }
Esempio n. 10
0
        public void SparqlJsonResultSet()
        {
            Console.WriteLine("Tests that JSON Parser parses language specifiers correctly");

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

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

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

            Object results = store.ExecuteQuery(query);

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

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

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

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

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

                Console.WriteLine("Result Sets were equal as expected");
            }
            else
            {
                Assert.Fail("Query did not return a Result Set");
            }
        }
Esempio n. 11
0
        public void SparqlGroupByRefactor8()
        {
            String query = @"PREFIX : <http://example.org/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

SELECT ?o ?x (COALESCE(?o / ?x, -2 ) AS ?div)
FROM <http://data-coalesce.ttl>
WHERE
{
  ?s :p ?o .
  OPTIONAL { ?s :q ?x . }
}";

            String data = @"<http://example.org/n0> <http://example.org/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n1> <http://example.org/p> ""0""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n1> <http://example.org/q> ""0""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n2> <http://example.org/p> ""0""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n2> <http://example.org/q> ""2""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n3> <http://example.org/p> ""4""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n3> <http://example.org/q> ""2""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .";

            TripleStore store = new TripleStore();

            StringParser.ParseDataset(store, data, new NQuadsParser());

            SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;

            Assert.IsNotNull(results);
            TestTools.ShowResults(results);
            Assert.AreEqual(4, results.Count);
            Assert.AreEqual(3, results.Variables.Count());

            foreach (SparqlResult r in results)
            {
                if (r.HasBoundValue("x"))
                {
                    long xVal = r["x"].AsValuedNode().AsInteger();
                    if (xVal == 0)
                    {
                        Assert.AreEqual(-2, r["div"].AsValuedNode().AsInteger(), "Divide by zero did not get coalesced to -2 as expected");
                    }
                    else
                    {
                        Assert.AreEqual(r["o"].AsValuedNode().AsInteger() / xVal, r["div"].AsValuedNode().AsInteger(), "Division yielded incorrect result");
                    }
                }
                else
                {
                    Assert.AreEqual(-2, r["div"].AsValuedNode().AsInteger(), "Divide by null did not get coalesced to -2 as expected");
                }
            }
        }
Esempio n. 12
0
        public void SparqlGroupByRefactor9()
        {
            try
            {
                //Options.UsePLinqEvaluation = false;

                String query = @"PREFIX : <http://example.org/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

SELECT (COALESCE(?x, -1 ) AS ?cx) (COALESCE(?o / ?x, -2 ) AS ?div)
(COALESCE(?z, -3 ) AS ?def)
(COALESCE(?z) AS ?err)
FROM <http://data-coalesce.ttl>
WHERE
{
  ?s :p ?o .
  OPTIONAL { ?s :q ?x . }
}";

                String data = @"<http://example.org/n0> <http://example.org/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n1> <http://example.org/p> ""0""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n1> <http://example.org/q> ""0""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n2> <http://example.org/p> ""0""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n2> <http://example.org/q> ""2""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n3> <http://example.org/p> ""4""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .
<http://example.org/n3> <http://example.org/q> ""2""^^<http://www.w3.org/2001/XMLSchema#integer> <http://data-coalesce.ttl> .";

                TripleStore store = new TripleStore();
                StringParser.ParseDataset(store, data, new NQuadsParser());

                SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;
                Assert.IsNotNull(results);
                TestTools.ShowResults(results);
                Assert.AreEqual(4, results.Count);
                Assert.AreEqual(4, results.Variables.Count());

                foreach (SparqlResult r in results)
                {
                    long cxVal = r["cx"].AsValuedNode().AsInteger();
                    if (cxVal == -1)
                    {
                        Assert.AreEqual(-2, r["div"].AsValuedNode().AsInteger(), "?div value is incorrect");
                    }
                }
            }
            finally
            {
                //Options.UsePLinqEvaluation = true;
            }
        }
Esempio n. 13
0
        public void SparqlSimpleQuery1()
        {
            if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing))
            {
                throw new SkipTestException("Test Config marks Remote Parsing as unavailable, test cannot be run");
            }

            TripleStore store = new TripleStore();

            store.AddFromUri(new Uri("http://dbpedia.org/resource/Barack_Obama"));
            const string      sparqlQuery  = "SELECT * WHERE {?s ?p ?o}";
            SparqlQueryParser sparqlParser = new SparqlQueryParser();
            SparqlQuery       query        = sparqlParser.ParseFromString(sparqlQuery);
            Object            results      = store.ExecuteQuery(query);
        }
        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");
            }
        }
Esempio n. 15
0
        public void WritingSparqlXmlWithSpecialCharacters()
        {
            TripleStore store = new TripleStore();

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

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

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

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

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

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

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

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

                Assert.AreEqual(rset, rset2, "Result Sets should be equal");
            }
            else
            {
                Assert.Fail("Query did not return a Result Set as expected");
            }
        }
Esempio n. 16
0
        public void SparqlAggregatesMaxBug2()
        {
            TripleStore store = new TripleStore();

            store.LoadFromFile("LearningStyles.rdf");

            IGraph graph = store.ExecuteQuery(@"prefix sage:
<http://www.semanticsage.home.lc/LearningStyles.owl#>
prefix xsd: <http://www.w3.org/2001/XMLSchema#>
prefix : <http://semanticsage.home.lc/files/LearningStyles.rdf#>

CONSTRUCT
{
    ?MTech :max ?maxScore
}
WHERE
{
    SELECT ?MTech max(?max) as ?maxScore
    WHERE
    {
        SELECT ?MTech ?LessonType sum(?hasValue) as ?max
        WHERE
        {
            ?MTech sage:attendsLessons ?Lesson.
            ?Lesson sage:hasLessonType ?LessonType.
            ?MTech sage:undergoesEvaluation ?Quiz.
            ?Quiz sage:isForLesson ?Lesson.
            ?MTech sage:hasQuizMarks ?QuizMarks.
            ?QuizMarks sage:belongsToQuiz ?Quiz.
            ?QuizMarks sage:hasValue ?hasValue.
            ?Lesson sage:inRound '1'^^xsd:int.
        }
        GROUP BY ?MTech ?LessonType
    }
    GROUP BY ?MTech
}") as IGraph;

            Assert.IsNotNull(graph);

            INode zero = (0).ToLiteral(graph);

            foreach (Triple t in graph.Triples)
            {
                Assert.IsFalse(t.Object.CompareTo(zero) == 0, "Unexpected zero value returned");
            }
        }
Esempio n. 17
0
        public IActionResult LoadFileG()
        {
            TripleStore store = new TripleStore();


            IGraph g = new Graph();

            NTriplesParser ntparser = new NTriplesParser();

            //Load using Filename
            ntparser.Load(g, new StreamReader("Data/anime_dataset.nt"));
            g.NamespaceMap.AddNamespace("schema", new Uri("http://schema.org/"));
            store.Add(g);

            /*
             * ITripleFormatter formatter = new TurtleFormatter(g);
             * Console.WriteLine("------------------------");
             * //Print triples with this formatter
             * foreach (Triple t in g.Triples)
             * {
             *  Console.WriteLine(t.ToString());
             * }
             */


            //Execute a raw SPARQL Query
            //Should get a SparqlResultSet back from a SELECT query

            Object results = store.ExecuteQuery("PREFIX schema: <http://schema.org/> SELECT * WHERE {?iri a schema:TVSeries .?iri schema:image ?image.}LIMIT 10");


            if (results is SparqlResultSet)
            {
                //Print out the Results
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result.ToString());
                }
            }


            return(View());
        }
Esempio n. 18
0
        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.IsFalse(((SparqlResultSet)results).Result);
            }
            else
            {
                Assert.Fail("ASK Query did not return a SPARQL Result Set as expected");
            }
        }
Esempio n. 19
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");
            }
        }
Esempio n. 20
0
        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");
            }
        }
Esempio n. 21
0
        public void SparqlGroupByRefactor3()
        {
            String query = @"BASE <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/algebra/manifest#>
PREFIX : <http://example/>

SELECT ?x ?y ?z FROM <http://join-combo-graph-2.ttl>
FROM NAMED <http://join-combo-graph-1.ttl>
WHERE
{ 
  GRAPH ?g { ?x ?p 1  . } 
  { ?x :p ?y . } UNION { ?p a ?z . } 
}";

            String data = @"<http://example/x1> <http://example/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x1> <http://example/r> ""4""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x2> <http://example/p> ""2""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x2> <http://example/r> ""10""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x2> <http://example/x> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x3> <http://example/q> ""3""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x3> <http://example/q> ""4""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x3> <http://example/s> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-2.ttl> .
<http://example/x3> <http://example/t> <http://example/s> <http://join-combo-graph-2.ttl> .
<http://example/p> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> <http://join-combo-graph-2.ttl> .
<http://example/x1> <http://example/z> <http://example/p> <http://join-combo-graph-2.ttl> .
<http://example/b> <http://example/p> ""1""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-1.ttl> .
_:a <http://example/p> ""9""^^<http://www.w3.org/2001/XMLSchema#integer> <http://join-combo-graph-1.ttl> .";

            TripleStore store = new TripleStore();

            StringParser.ParseDataset(store, data, new NQuadsParser());

            SparqlResultSet results = store.ExecuteQuery(query) as SparqlResultSet;

            Assert.IsNotNull(results);
            TestTools.ShowResults(results);
            Assert.AreEqual(1, results.Count);
            Assert.AreEqual(3, results.Variables.Count());
        }
Esempio n. 22
0
        public ISparqlQueryResult ExecuteQuery(ISparqlQuery query, ITransaction transaction = null)
        {
            if (query.IsInferenceEnabled && _reasoner != null)
            {
                _store.AddInferenceEngine(_reasoner);
            }
            else
            {
                _store.ClearInferenceEngines();
            }

            object results = _store.ExecuteQuery(query.ToString());

            if (results is IGraph)
            {
                return(new dotNetRDFQueryResult(this, query, results as IGraph));
            }
            else if (results is SparqlResultSet)
            {
                return(new dotNetRDFQueryResult(this, query, results as SparqlResultSet));
            }

            return(null);
        }
Esempio n. 23
0
        public void SparqlGroupByWithGraph1()
        {
            String query = @"SELECT ?g WHERE { GRAPH ?g { } } GROUP BY ?g";

            TripleStore store = new TripleStore();
            IGraph      def   = new Graph();

            store.Add(def);
            IGraph named = new Graph();

            named.BaseUri = new Uri("http://name");
            store.Add(named);

            Assert.AreEqual(2, store.Graphs.Count);

            SparqlQuery     q       = new SparqlQueryParser().ParseFromString(query);
            SparqlResultSet results = store.ExecuteQuery(q) as SparqlResultSet;

            Assert.IsNotNull(results);
            Assert.IsFalse(results.IsEmpty);

            //Count only covers named graphs
            Assert.AreEqual(1, results.Count);
        }
Esempio n. 24
0
        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");
            }
        }
Esempio n. 25
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");
            }
        }
Esempio n. 26
0
        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);
                }
            }
        }
Esempio n. 27
0
        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))));
        }
Esempio n. 28
0
        private SparqlResultSet ExecuteQuery(string query)
        {
            var result = store.ExecuteQuery(prefixes + query);

            return((SparqlResultSet)result);
        }
Esempio n. 29
0
        public void SparqlBgpEvaluation()
        {
            //Prepare the Store
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "resources\\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 VariableTerm("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))));
        }
Esempio n. 30
0
        public void SparqlPropertyPathParser()
        {
            //Load our test data
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "resources\\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);
                }
            }
        }
Esempio n. 31
0
        public void RunTest(String[] args)
        {
            if (args.Length < 2)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -test mode");
                return;
            }

            if (!File.Exists(args[1]))
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot test " + args[1] + " since the file does not exist");
                return;
            }

            Graph g = new Graph();

            try
            {
                FileLoader.Load(g, args[1]);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot parse the configuration file");
                Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message);
                return;
            }
            Console.WriteLine("rdfWebDeploy: Opened the configuration file successfully");

            Graph vocab = new Graph();

            try
            {
                vocab.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
                vocab.LoadFromEmbeddedResource("VDS.RDF.Query.FullText.ttl, dotNetRDF.Query.FullText");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot parse the configuration vocabulary");
                Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message);
                return;
            }
            Console.WriteLine("rdfWebDeploy: Loaded the configuration vocabulary successfully");
            Console.WriteLine();
            Console.WriteLine("rdfWebDeploy: Tests Started...");
            Console.WriteLine();

            //Now make some tests against it
            int warnings = 0, errors = 0;
            IInMemoryQueryableStore store = new TripleStore();

            store.Add(vocab);
            if (g.BaseUri == null)
            {
                g.BaseUri = new Uri("dotnetrdf:config");
            }
            store.Add(g);
            Object          results;
            SparqlResultSet rset;

            //Unknown vocabulary term test
            Console.WriteLine("rdfWebDeploy: Testing for URIs in the vocabulary namespace which are unknown");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + UnknownVocabularyTermsTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The configuration file uses the URI '" + r["term"] + "' for a property/type and this does not appear to be a valid term in the Configuration vocabulary");
                    errors++;
                }
            }
            Console.WriteLine();

            #region General dnr:type Tests

            //Missing dnr:type test
            Console.WriteLine("rdfWebDeploy: Testing for missing dnr:type properties");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + MissingConfigurationTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Warning: The Node '" + r["s"].ToString() + "' has an rdf:type but no dnr:type which may be needed by the Configuration Loader");
                    warnings++;
                }
            }
            Console.WriteLine();

            //Invalid dnr:type test
            Console.WriteLine("rdfWebDeploy: Testing that values given for dnr:type property are literals");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidTypePropertyTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which is not given as a string literal");
                    errors++;
                }
            }
            Console.WriteLine();

            //Multiple dnr:type test
            Console.WriteLine("rdfWebDeploy: Testing that no object has multiple dnr:type values");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + MultipleTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has multiple dnr:type values which is not valid");
                    errors++;
                }
            }
            Console.WriteLine();

            //Unknown Library Types test
            Console.WriteLine("rdfWebDeploy: Testing that values given for dnr:type property are valid");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + LibraryTypesTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                Assembly dotnetrdf = Assembly.GetAssembly(typeof(IGraph));

                foreach (SparqlResult r in rset)
                {
                    String typeName = ((ILiteralNode)r["type"]).Value;
                    Type   t        = typeName.Contains(",") ? Type.GetType(typeName) : dotnetrdf.GetType(typeName);

                    if (t == null)
                    {
                        Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which does not appear to be a valid type in an available DLL");
                        errors++;
                    }
                    else
                    {
                        if (typeName.Contains(","))
                        {
                            String assm = typeName.Substring(typeName.IndexOf(",") + 1);
                            assm = assm.Trim();

                            switch (assm)
                            {
                            case "dotNetRDF.Data.Sql":
                                Console.Error.WriteLine("rdfWebDeploy: Warning: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which is in the dotNetRDF.Data.Sql library, please ensure you use the -sql option when deploying or if deploying manually include the Data.Sql library and its dependencies");
                                warnings++;
                                break;

                            case "dotNetRDF.Data.Virtuoso":
                                Console.Error.WriteLine("rdfWebDeploy: Warning: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which is in the dotNetRDF.Data.Virtuoso library, please ensure you use the -virtuoso option when deploying or if deploying manually include the Data.Virtuoso library and its dependencies");
                                warnings++;
                                break;

                            case "dotNetRDF.Query.FullText":
                                Console.Error.WriteLine("rdfWebDeploy: Warning: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which is in the dotNetRDF.Query.FullText library, please ensure you use the -fulltext option when deploying or if deploying manually include the Query.FullText library and its dependencies");
                                warnings++;
                                break;

                            default:
                                Console.Error.WriteLine("rdfWebDeploy: Warning: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which is in the " + assm + " library, please ensure that when deploying you manually include this library and any dependencies");
                                warnings++;
                                break;
                            }
                        }
                    }
                }
            }
            Console.WriteLine();

            #endregion

            #region dnr:HttpHandler Tests including specific dnr:type Tests

            //Bad Handler URI test
            Console.WriteLine("rdfWebDeploy: Testing for bad URIs given the rdf:type of dnr:HttpHandler");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + BadHandlerUriTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The Handler node '" + r["s"].ToString() + "' is not a URI of the form <dotnetrdf:/path> which is required for correct detection of handler configuration");
                    errors++;
                }
            }
            Console.WriteLine();

            //Missing Handler type test
            Console.WriteLine("rdfWebDeploy: Testing for missing dnr:type for dnr:HttpHandler objects");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + MissingHandlerTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The Handler node '" + r["s"].ToString() + "' has an rdf:type but no dnr:type which is requiring for automated deployment via this tool");
                    errors++;
                }
            }
            Console.WriteLine();

            //Invalid Handler Type test
            Console.WriteLine("rdfWebDeploy: Testing that values given for dnr:type for dnr:HttpHandler objects in the VDS.RDF namespace are valid IHttpHandlers");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidHandlerTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                Assembly dotnetrdf = Assembly.GetAssembly(typeof(IGraph));
                foreach (SparqlResult r in rset)
                {
                    Type t = dotnetrdf.GetType(((ILiteralNode)r["type"]).Value);
                    if (t != null)
                    {
                        if (!t.GetInterfaces().Any(i => i.Equals(typeof(System.Web.IHttpHandler))))
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which does not appear to be a valid IHttpHandler implementation in dotNetRDF");
                            errors++;
                        }
                    }
                }
            }
            Console.WriteLine();

            #endregion

            #region Property Tests

            //Range test
            Console.WriteLine("rdfWebDeploy: Testing for bad ranges for properties");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidRangeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    SparqlParameterizedString hasValidRange = new SparqlParameterizedString();
                    hasValidRange.CommandText = RdfWebDeployHelper.NamespacePrefixes + ValidRangeTest;
                    hasValidRange.SetParameter("property", r["property"]);
                    hasValidRange.SetParameter("s", r["s"]);
                    Object temp = store.ExecuteQuery(hasValidRange.ToString());
                    if (temp is SparqlResultSet)
                    {
                        if (!((SparqlResultSet)temp).Result)
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: The Node '" + r["s"].ToString() + "' has a value for the property '" + r["property"].ToString() + "' which is '" + r["obj"].ToString() + "' which does not appear to be valid for the range of this property which is '" + r["range"].ToString() + "'");
                            errors++;
                        }
                    }
                }
            }
            Console.WriteLine();

            //Domain test
            Console.WriteLine("rdfWebDeploy: Testing for bad domains for properties");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidDomainTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    SparqlParameterizedString hasValidDomain = new SparqlParameterizedString();
                    hasValidDomain.CommandText = RdfWebDeployHelper.NamespacePrefixes + ValidDomainTest;
                    hasValidDomain.SetParameter("property", r["property"]);
                    hasValidDomain.SetParameter("s", r["s"]);
                    Object temp = store.ExecuteQuery(hasValidDomain.ToString());
                    if (temp is SparqlResultSet)
                    {
                        if (!((SparqlResultSet)temp).Result)
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: The Node '" + r["s"].ToString() + "' has a value for the property '" + r["property"].ToString() + "' and the type given is '" + r["type"].ToString() + "' which does not match the domain of this property which is '" + r["domain"].ToString() + "'");
                            errors++;
                        }
                    }
                }
            }
            Console.WriteLine();

            #endregion

            #region Clear Text Password Tests

            Console.WriteLine("rdfWebDeploy: Testing for clear text passwords used with dnr:password property");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + ClearTextPasswordTest);
            if (results is SparqlResultSet)
            {
                foreach (SparqlResult r in (SparqlResultSet)results)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Warning: The Node '" + r["s"].ToString() + "' has a value for the dnr:password property specified as a Literal in clear text.  It is recommended that you specify any passwords as AppSetting URIs e.g. <appsetting:MyPassword> and then create an AppSetting in the <appSettings> section of your Web.config file to store your password.  The Web.config file can then have the <appSettings> section encrypted to help protect your password");
                    warnings++;
                }
            }
            Console.WriteLine();

            #endregion

            //Show Test Results
            Console.WriteLine("rdfWedDeploy: Tests Completed - " + warnings + " Warning(s) - " + errors + " Error(s)");
        }
Esempio n. 32
0
        public void SparqlAggregatesMaxBug3()
        {
            try
            {
                Options.AlgebraOptimisation = false;

                TripleStore store = new TripleStore();
                Graph       g     = new Graph();
                g.LoadFromFile("LearningStyles.rdf");
                Assert.IsFalse(g.IsEmpty);
                g.BaseUri = null;
                store.Add(g);

                var graph = (IGraph)store.ExecuteQuery(@"
                    PREFIX sage: <http://www.semanticsage.home.lc/LearningStyles.owl#>
                    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
                    PREFIX : <http://www.semanticsage.home.lc/LearningStyles.rdf#>
                    CONSTRUCT 
                    { 
                       ?MTech :max ?maxScore  
                    }
                    WHERE 
                    { 
                       SELECT ?MTech (MAX(?max) AS ?maxScore)
                       WHERE
                       {
                          SELECT ?MTech ?LessonType (SUM(?hasValue) AS ?max)
                          WHERE 
                          {
                             ?MTech sage:attendsLessons ?Lesson. 
                             ?Lesson sage:hasLessonType ?LessonType. 
                             ?MTech sage:undergoesEvaluation ?Quiz. 
                             ?Quiz sage:isForLesson ?Lesson. 
                             ?MTech sage:hasQuizMarks ?QuizMarks. 
                             ?QuizMarks sage:belongsToQuiz ?Quiz. 
                             ?QuizMarks sage:hasValue ?hasValue.
                             ?Lesson sage:inRound '1'^^xsd:int.
                          }
                          GROUP BY ?MTech ?LessonType
                       }
                       GROUP BY ?MTech
                    }");

                Assert.IsFalse(graph.IsEmpty, "CONSTRUCTed graph should not be empty");

                // here a graph name is given to the result graph
                graph.BaseUri = new Uri("http://semanticsage.home.lc/files/LearningStyles.rdf#maxValues");
                store.Add(graph, true);

                SparqlResultSet actualResults = store.ExecuteQuery(@"
                    PREFIX sage: <http://www.semanticsage.home.lc/LearningStyles.owl#>
                    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
                    PREFIX : <http://www.semanticsage.home.lc/LearningStyles.rdf#>
                    SELECT ?MTech ?LessonType ?max
                    WHERE
                    {
                       GRAPH <http://semanticsage.home.lc/files/LearningStyles.rdf#maxValues>
                       {
                          ?MTech :max ?max
                       }
                       {
                            SELECT ?MTech ?LessonType (SUM(?hasValue) AS ?Score)
                            WHERE 
                            {
                                ?MTech sage:attendsLessons ?Lesson. 
                                ?Lesson sage:hasLessonType ?LessonType. 
                                ?MTech sage:undergoesEvaluation ?Quiz. 
                                ?Quiz sage:isForLesson ?Lesson. 
                                ?MTech sage:hasQuizMarks ?QuizMarks. 
                                ?QuizMarks sage:belongsToQuiz ?Quiz. 
                                ?QuizMarks sage:hasValue ?hasValue.
                                ?Lesson sage:inRound '1'^^xsd:int.
                            }
                            GROUP BY ?MTech ?LessonType
                            ORDER BY ?MTech
                       }
                       FILTER(?Score = ?max)
                    }") as SparqlResultSet;
                Assert.IsNotNull(actualResults);
                Assert.IsFalse(actualResults.IsEmpty, "Final results should not be empty");
            }
            finally
            {
                Options.AlgebraOptimisation = true;
            }
        }