private void TestConstruct(IInMemoryQueryableStore store, IGraph expected, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store);
            Object results = processor.ProcessQuery(q);
            if (results is IGraph)
            {
                IGraph result = (IGraph)results;

                NTriplesFormatter formatter = new NTriplesFormatter();
                Console.WriteLine("Result Data");
                foreach (Triple t in result.Triples)
                {
                    Console.WriteLine(t.ToString(formatter));
                }
                Console.WriteLine();

                Console.WriteLine("Expected Data");
                foreach (Triple t in expected.Triples)
                {
                    Console.WriteLine(t.ToString(formatter));
                }
                Console.WriteLine();

                Assert.AreEqual(expected, result, "Graphs should be equal");
            }
            else
            {
                Assert.Fail("Did not get a Graph as expected");
            }
        }
        public void SparqlDefaultGraphExists3()
        {
            SqlDataset dataset = new SqlDataset(new MicrosoftSqlStoreManager("localhost", "unit_test", "example", "password"));

            //Create Default Graph only if required
            if (!dataset.HasGraph(null))
            {
                Graph g = new Graph();
                g.Assert(g.CreateUriNode(new Uri("http://example.org/subject")), g.CreateUriNode(new Uri("http://example.org/predicate")), g.CreateUriNode(new Uri("http://example.org/object")));
                dataset.AddGraph(g);
                dataset.Flush();
            }

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

            dataset.Flush();
        }
 static object Execute(TripleStore store, string sparql)
 {
     InMemoryDataset ds = new InMemoryDataset(store);
     ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);
     SparqlQueryParser sparqlparser = new SparqlQueryParser();
     SparqlQuery query = sparqlparser.ParseFromString(sparql);
     return processor.ProcessQuery(query);
 }
        private void TestBindings(ISparqlDataset data, String queryWithBindings, String queryWithoutBindings)
        {
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(data);
            SparqlQuery bindingsQuery = this._parser.ParseFromString(queryWithBindings);
            SparqlQuery noBindingsQuery = this._parser.ParseFromString(queryWithoutBindings);

            SparqlResultSet bindingsResults = processor.ProcessQuery(bindingsQuery) as SparqlResultSet;
            SparqlResultSet noBindingsResults = processor.ProcessQuery(noBindingsQuery) as SparqlResultSet;

            if (bindingsResults == null) Assert.Fail("Did not get a SPARQL Result Set for the Bindings Query");
            if (noBindingsResults == null) Assert.Fail("Did not get a SPARQL Result Set for the Non-Bindings Query");

            Console.WriteLine("Bindings Results");
            TestTools.ShowResults(bindingsResults);
            Console.WriteLine();
            Console.WriteLine("Non-Bindings Results");
            TestTools.ShowResults(noBindingsResults);
            Console.WriteLine();

            Assert.AreEqual(noBindingsResults, bindingsResults, "Result Sets should have been equal");
        }
Example #5
0
        /// <summary>
        /// Constructs querying function for BrightstarDB
        /// </summary>
        /// <returns>Querying function</returns>
        public Func<string, SPARQLQueryResults> GetQueryingFunction()
        {
            Func<string, SPARQLQueryResults> queringFunction = xquery =>
            {
                var queryProcessor = new LeviathanQueryProcessor(Dataset);
                var dnRdfResultSet = queryProcessor.ProcessQuery(new SparqlQueryParser().ParseFromString(xquery)) as SparqlResultSet;
                var results = new SPARQLQueryResults();

                foreach (var dnRdfVariable in dnRdfResultSet.Variables)
                    results.Variables.Add(dnRdfVariable);

                foreach (var dnRdfResult in dnRdfResultSet)
                {
                    var result = new SPARQLQueryResult();

                    foreach (var node in dnRdfResult)
                    {
                        ResultBinding binding = null;

                        if (node.Value.NodeType == VDS.RDF.NodeType.Uri)
                        {
                            var uriNode = node.Value as IUriNode;
                            var iriBinding = new IriBinding();
                            iriBinding.Iri = uriNode.Uri;
                            binding = iriBinding;
                        }
                        else if (node.Value.NodeType == VDS.RDF.NodeType.Literal)
                        {
                            var literalNode = node.Value as ILiteralNode;
                            var litBinding = new LiteralBinding();
                            litBinding.DataType = literalNode.DataType;
                            litBinding.Language = literalNode.Language;
                            litBinding.Literal = literalNode.Value;
                            binding = litBinding;
                        }
                        else
                            binding = new LiteralBinding();

                        binding.Name = node.Key;
                        result.AddBinding(binding);
                    }

                    results.AddResult(result);
                }

                return results;
            };

            return queringFunction;
        }
        public void FullTextGraphSparqlScoping5()
        {
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(this._store);

            //Interaction of graph scope with limit
            using (LuceneSearchProvider searcher = new LuceneSearchProvider(LucUtil.Version.LUCENE_30, this._index, new StandardAnalyzer(LucUtil.Version.LUCENE_30)))
            {
                SparqlQuery q = this._parser.ParseFromString(FullTextPrefix + " SELECT * WHERE { GRAPH <http://g2> { ?s pf:textMatch ( 'sample' 1 ) } }");
                q.AlgebraOptimisers = new IAlgebraOptimiser[] { new FullTextOptimiser(searcher) };

                SparqlResultSet results = processor.ProcessQuery(q) as SparqlResultSet;
                Assert.NotNull(results);
                Assert.Equal(1, results.Count);
                Assert.Equal(new Uri("http://y"), ((IUriNode)results.First()["s"]).Uri);
            }
        }
Example #7
0
        public void SparqlServiceUsingDBPediaAndBindings()
        {
            String query = "SELECT * WHERE { SERVICE <http://dbpedia.org/sparql> { ?s a ?type } } BINDINGS ?s { ( <http://dbpedia.org/resource/Southampton> ) ( <http://dbpedia.org/resource/Ilkeston> ) }";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(new TripleStore());
            Object results = processor.ProcessQuery(q);
            if (results is SparqlResultSet)
            {
                TestTools.ShowResults(results);
            }
            else
            {
                Assert.Fail("Should have returned a SPARQL Result Set");
            }
        }
Example #8
0
        static void AQuery()
        {
            IGraph g = new Graph();

            Notation3Parser n3parser = new Notation3Parser();

            try
            {
                //Load using Filename
                n3parser.Load(g, "szepmuveszeti.n3");
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }
            TripleStore store = new TripleStore();

            store.Add(g);
            ISparqlDataset ds = new InMemoryDataset(g);

            //Get the Query processor
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(ds);

            SparqlQuery q       = new SparqlQueryParser().ParseFromString("PREFIX ecrm:<http://erlangen-crm.org/current/> SELECT ?actor {?actor a ecrm:E39_Actor}");
            Object      results = processor.ProcessQuery(q);

            if (results is SparqlResultSet)
            {
                //Print out the Results
                //Console.WriteLine("working up to this ");
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult result in rset.Results)
                {
                    Console.WriteLine(result.ToString());
                }
            }
        }
Example #9
0
        public void SparqlServiceWithNonExistentService()
        {
            String query = "SELECT * WHERE { SERVICE <http://www.dotnetrdf.org/noSuchService> { ?s a ?type } } LIMIT 10";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(new TripleStore());
            try
            {
                Object results = processor.ProcessQuery(q);
                Assert.Fail("Should have errored");
            }
            catch (RdfQueryException queryEx)
            {
                Console.WriteLine("Errored as expected");
                TestTools.ReportError("Query Error", queryEx, false);
            }
        }
Example #10
0
        public void SparqlFilterLazy3()
        {
            long currTimeout = Options.QueryExecutionTimeout;

            try
            {
                Options.QueryExecutionTimeout = 0;

                String query = "SELECT * WHERE { ?s a ?vehicle . FILTER (SAMETERM(?vehicle, <http://example.org/vehicles/Car>)) . ?s <http://example.org/vehicles/Speed> ?speed } LIMIT 3";

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

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

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

                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));
                Object results = processor.ProcessQuery(q);
                if (results is SparqlResultSet)
                {
                    SparqlResultSet rset = (SparqlResultSet)results;
                    foreach (SparqlResult r in rset)
                    {
                        Console.WriteLine(r.ToString());
                    }
                    Assert.IsTrue(rset.Count == 3, "Expected exactly 3 results");
                }
                else
                {
                    Assert.Fail("Expected a SPARQL Result Set");
                }
            }
            finally
            {
                Options.QueryExecutionTimeout = currTimeout;
            }
        }
Example #11
0
        public static SparqlResultSet PerformQuery(string q, Graph g)
        {
            SparqlParameterizedString queryString = new SparqlParameterizedString();

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

            TripleStore store = new TripleStore();

            store.Add(g);

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

            return(results);
        }
 public IEnumerable<IDataObject> BindRdfDataObjects(IGraph g,
                                                    IList<OrderingDirection> orderingDirections)
 {
     var p = new LeviathanQueryProcessor(new InMemoryDataset(g));
     var queryString = MakeOrderedResourceQuery(orderingDirections);
     var sparqlParser = new SparqlQueryParser();
     var query = sparqlParser.ParseFromString(queryString);
     var queryResultSet = p.ProcessQuery(query) as SparqlResultSet;
     if (queryResultSet != null)
     {
         foreach (var row in queryResultSet.Results)
         {
             INode uriNode;
             if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode)
             {
                 yield return BindRdfDataObject((IUriNode) uriNode, g);
             }
         }
     }
 } 
Example #13
0
        public static void ApplyInference(IGraph graph, IGraph schema)
        {
            string inverseOf = @"
                PREFIX owl: <http://www.w3.org/2002/07/owl#>
                CONSTRUCT { ?y ?q ?x }
                WHERE { ?p owl:inverseOf ?q .
                        ?x ?p ?y . }
            ";

            var parser = new SparqlQueryParser();

            var rules = new List <SparqlQuery>();

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

            var store = new TripleStore();

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

            var queryProcessor = new LeviathanQueryProcessor(store);

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

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

                int after = store.Triples.Count();

                if (after == before)
                {
                    break;
                }
            }
        }
        public IEnumerable <IDataObject> BindRdfDataObjects(IGraph g,
                                                            IList <OrderingDirection> orderingDirections)
        {
            var p              = new LeviathanQueryProcessor(new InMemoryDataset(g));
            var queryString    = MakeOrderedResourceQuery(orderingDirections);
            var sparqlParser   = new SparqlQueryParser();
            var query          = sparqlParser.ParseFromString(queryString);
            var queryResultSet = p.ProcessQuery(query) as SparqlResultSet;

            if (queryResultSet != null)
            {
                foreach (var row in queryResultSet.Results)
                {
                    INode uriNode;
                    if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode)
                    {
                        yield return(BindRdfDataObject((IUriNode)uriNode, g));
                    }
                }
            }
        }
        public string QueryTripleStoreRaw(SparqlParameterizedString queryString)
        {
            var processor = new LeviathanQueryProcessor(_dataset);

            var sparqlParser = new SparqlQueryParser();

            AddAllPidNamespaces(queryString);

            var query = sparqlParser.ParseFromString(queryString);

            //Object results = _store.ExecuteQuery(query);
            Object results = processor.ProcessQuery(query);

            if (results is IGraph)
            {
                IGraph g = (IGraph)results;
                return(ConvertGraphToString(g));
            }

            throw new System.Exception("Execute failed");
        }
        public SparqlResultSet QueryTripleStoreResultSet(SparqlParameterizedString parameterizedString)
        {
            var processor = new LeviathanQueryProcessor(_dataset);

            var sparqlParser = new SparqlQueryParser();

            AddAllPidNamespaces(parameterizedString);

            var query = sparqlParser.ParseFromString(parameterizedString);

            Object results = processor.ProcessQuery(query);

            //Object results = _store.ExecuteQuery(query);

            if (results is SparqlResultSet rset)
            {
                //Print out the Results
                return(rset);
            }

            return(null);
        }
Example #17
0
        public void TestSubjPatternObjLiteral()
        {
            string      queryStr = @"SELECT *
                                 WHERE { ?usr <http://www.semanticweb.org/LMS/User#NAME> ""Alexander Cole""}";
            SparqlQuery query    = null;
            TripleStore store    = null;

            Arrange(queryStr, out store, out query);

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

            //ASSERT
            Assert.IsInstanceOfType(results, typeof(SparqlResultSet));

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                Assert.IsTrue(rset.Count == 1);
            }
        }
Example #18
0
        public static void ApplyInference(IGraph graph, IGraph schema)
        {
            string inverseOf = @"
                PREFIX owl: <http://www.w3.org/2002/07/owl#>
                CONSTRUCT { ?y ?q ?x }
                WHERE { ?p owl:inverseOf ?q .
                        ?x ?p ?y . }
            ";

            var parser = new SparqlQueryParser();

            var rules = new List<SparqlQuery>();
            rules.Add(parser.ParseFromString(inverseOf));

            var store = new TripleStore();
            store.Add(graph, true);
            store.Add(schema, true);

            var queryProcessor = new LeviathanQueryProcessor(store);

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

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

                int after = store.Triples.Count();

                if (after == before)
                {
                    break;
                }
            }
        }
        public static List <SparqlResult> RunQuery(string url, string queryString)
        {
            TripleStore store = new TripleStore();

            //Assume that we fill our Store with data from somewhere

            //Create a dataset for our queries to operate over
            //We need to explicitly state our default graph or the unnamed graph is used
            //Alternatively you can set the second parameter to true to use the union of all graphs
            //as the default graph
            InMemoryDataset ds = new InMemoryDataset(store, new Uri(url));

            //Get the Query processor
            ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);

            //Use the SparqlQueryParser to give us a SparqlQuery object
            //Should get a Graph back from a CONSTRUCT query

            SparqlQueryParser sparqlparser = new SparqlQueryParser();
            SparqlQuery       query        = sparqlparser.ParseFromString(queryString);
            var result = processor.ProcessQuery(query);

            if (result is SparqlResultSet)
            {
                var results = (SparqlResultSet)result;
                return(results.ToList());
            }

            //if (result is IGraph)
            //{
            //    //Print out the Results
            //    IGraph g = (IGraph)result;
            //    NTriplesFormatter formatter = new NTriplesFormatter();
            //    return g.Triples.ToList();
            //}

            return(null);
        }
        public IGraph QueryTripleStoreGraphResult(SparqlParameterizedString queryString)
        {
            var processor = new LeviathanQueryProcessor(_dataset);

            var sparqlParser = new SparqlQueryParser();

            AddAllPidNamespaces(queryString);

            var query = sparqlParser.ParseFromString(queryString);

            Object results = processor.ProcessQuery(query);

            //Object results = _store.ExecuteQuery(query);

            if (results is IGraph)
            {
                //Print out the Results
                IGraph rset = (VDS.RDF.Graph)results;
                return(rset);
            }

            return(null);
        }
        public LastBlockInfo GetLastBlockInfo()
        {
            _logger.LogDebug("Getting last block info...");
            string queryName = "get_last_block_info";

            _logger.LogTrace("Invoking the '{0}' SPARQL query...", queryName);
            string      query      = String.Format(_queryTemplatesService.GetQueryTemplate(queryName), _chainGraphIri);
            var         parser     = new SparqlQueryParser();
            SparqlQuery tupleQuery = parser.ParseFromString(query);
            var         processor  = new LeviathanQueryProcessor(_repository);
            var         resultSet  = processor.ProcessQuery(tupleQuery) as SparqlResultSet;

            if (resultSet.IsEmpty)
            {
                return(null);
            }
            var    bindingSet     = resultSet.Results[0];
            string lastBlockIri   = bindingSet.Value("lastBlockIRI").ToString();
            string lastBlockHash  = (bindingSet.Value("lastBlockHash") as ILiteralNode).Value;
            string lastBlockIndex = (bindingSet.Value("lastBlockIndex") as ILiteralNode).Value;

            return(new LastBlockInfo(lastBlockIri, lastBlockHash, lastBlockIndex));
        }
Example #22
0
        public void TestQueryBothKMS_LMS()
        {
            string      queryStr = @"SELECT *
                                    WHERE { ?usr <http://www.semanticweb.org/LMS/User#EMAIL> ?email.
                                            ?usr1 <http://www.semanticweb.org/KMS/User#EMAIL> ?email}";
            TripleStore store    = null;
            SparqlQuery query    = null;

            Arrange(queryStr, out store, out query);

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

            //ASSERT
            Assert.IsInstanceOfType(results, typeof(SparqlResultSet));

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                Assert.IsTrue(rset.Count == 7);
            }
        }
Example #23
0
        public void SparqlFilterLazyDBPedia()
        {
            SparqlParameterizedString query = new SparqlParameterizedString();

            query.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS));
            query.CommandText = "SELECT * WHERE {?s ?p ?label . FILTER(ISLITERAL(?label) && LANGMATCHES(LANG(?label), \"en\")) } LIMIT 5";

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

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

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

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

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

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
Example #24
0
        public void SparqlAggregatesOverNullCount1()
        {
            SparqlQuery     q       = _parser.ParseFromString("SELECT (COUNT(*) AS ?Count) WHERE { ?s ?p ?o }");
            SparqlResultSet results = _processor.ProcessQuery(q) as SparqlResultSet;

            Assert.NotNull(results);
            Assert.Equal(1, results.Count);

            SparqlResult r = results.First();

            Assert.Equal((0).ToLiteral(_factory), r["Count"]);
        }
        public void SparqlGraphClause4()
        {
            String query = "SELECT * WHERE { GRAPH ?g { ?s ?p ?o } }";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            InMemoryDataset dataset = new InMemoryDataset(false);
            IGraph ex = new Graph();
            FileLoader.Load(ex, "InferenceTest.ttl");
            ex.BaseUri = new Uri("http://example.org/graph");
            dataset.AddGraph(ex);

            IGraph def = new Graph();
            dataset.AddGraph(def);

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset);
            Object results = processor.ProcessQuery(q);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                TestTools.ShowResults(rset);
                Assert.AreEqual(ex.Triples.Count, rset.Count, "Number of Results should have been equal to number of Triples");
            }
            else
            {
                Assert.Fail("Did not get a SPARQL Result Set as expected");
            }
        }
        public void SparqlDatasetDefaultGraphManagement2()
        {
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            g.Assert(g.CreateUriNode(new Uri("http://example.org/subject")), g.CreateUriNode(new Uri("http://example.org/predicate")), g.CreateUriNode(new Uri("http://example.org/object")));
            store.Add(g);
            Graph h = new Graph();
            h.BaseUri = new Uri("http://example.org/someOtherGraph");
            store.Add(h);

            InMemoryDataset dataset = new InMemoryDataset(store);
            dataset.SetDefaultGraph(g);
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset);
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString("SELECT * WHERE { ?s ?p ?o }");

            Object results = processor.ProcessQuery(q);
            if (results is SparqlResultSet)
            {
                TestTools.ShowResults(results);
                Assert.IsFalse(((SparqlResultSet)results).IsEmpty, "Results should be false as a non-empty Graph was set as the Default Graph");
            }
            else
            {
                Assert.Fail("ASK Query did not return a SPARQL Result Set as expected");
            }
        }
Example #27
0
        /// <inheritdoc />
        public override bool ExecuteAsk(IQuery sparqlQuery)
        {
            SparqlQueryVariables variables;

            return(((SparqlResultSet)_processor.ProcessQuery(CreateSparqlQuery(sparqlQuery, out variables))).Result);
        }
Example #28
0
 public Object Evaluate(ISparqlDataset dataset)
 {
     LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset);
     return processor.ProcessQuery(this);
 }
Example #29
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;
            }
        }
        private SparqlResultSet ExecuteSelect(SparqlQuery query)
        {
            var store = _store as IInMemoryQueryableStore;
            if (store != null)
            {
                var inMemoryQuadDataset = new InMemoryQuadDataset(store, MetaGraphUri);
                var processor = new LeviathanQueryProcessor(inMemoryQuadDataset);
                return (SparqlResultSet)processor.ProcessQuery(query);
            }

            return (SparqlResultSet)((INativelyQueryableStore)_store).ExecuteQuery(query.ToString());
        }
Example #31
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);
            }
        }
Example #32
0
        public void SparqlOrderByComplexLazyPerformance()
        {
            String query = "SELECT * WHERE { ?s ?p ?o . } ORDER BY ?s DESC(?p) LIMIT 5";

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

            FileLoader.Load(g, "dataset_50.ttl.gz");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();

            //First do with Optimisation
            Stopwatch   timer = new Stopwatch();
            SparqlQuery q     = parser.ParseFromString(query);

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

            timer.Start();
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));
            Object results = processor.ProcessQuery(q);

            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Optimised");
            timer.Reset();
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }

            //Then do without optimisation
            Options.AlgebraOptimisation = false;
            timer.Start();
            results = processor.ProcessQuery(q);
            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Unoptimised");
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
            Options.AlgebraOptimisation = true;
        }
Example #33
0
 public void Evaluate(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, ISparqlDataset dataset)
 {
     LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset);
     processor.ProcessQuery(rdfHandler, resultsHandler, this);
 }
Example #34
0
        public void RunQuery(String[] args)
        {
            if (!this.SetOptions(args))
            {
                //Abort if we can't set options properly
                return;
            }

            //If no input URI/Query specified exit
            if (this._inputUri.Equals(String.Empty) && this._queryString.Equals(String.Empty))
            {
                Console.Error.WriteLine("rdfQuery: No Query Input URI of -e QUERY option was specified so nothing to do");
                return;
            }
            else if (!this._inputUri.Equals(String.Empty))
            {
                //Try and load the query from the File/URI
                try
                {
                    Uri u = new Uri(this._inputUri);
                    if (u.IsAbsoluteUri)
                    {
                        using (StreamReader reader = new StreamReader(HttpWebRequest.Create(this._inputUri).GetResponse().GetResponseStream()))
                        {
                            this._queryString = reader.ReadToEnd();
                        }
                    }
                    else
                    {
                        using (StreamReader reader = new StreamReader(this._inputUri))
                        {
                            this._queryString = reader.ReadToEnd();
                        }
                    }
                }
                catch (UriFormatException)
                {
                    using (StreamReader reader = new StreamReader(this._inputUri))
                    {
                        this._queryString = reader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("rdfQuery: Error: Unable to read the query from the URI '" + this._inputUri + "' due to the following error:");
                    Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
                    return;
                }
            }

            //Try to parse the query
            SparqlQuery q;
            try
            {
                q = this._parser.ParseFromString(this._queryString);
            }
            catch (RdfParseException parseEx)
            {
                Console.Error.WriteLine("rdfQuery: Parser Error: Unable to parse the query due to the following error:");
                Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message);
                return;
            }
            catch (RdfQueryException queryEx)
            {
                Console.Error.WriteLine("rdfQuery: Query Error: Unable to read the query due to the following error:");
                Console.Error.WriteLine("rdfQuery: Query Error: " + queryEx.Message);
                return;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfQuery: Error: Unable to read the query due to the following error:");
                Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
                return;
            }

            //If dumping/dry-running/walking then just print the appropriate debug stuff and exit
            if (this._dryrun || this._walk || this._dump)
            {
                if (this._dump || this._walk)
                {
                    switch (this._dumpFormat)
                    {
                        case "debug":
                            Console.WriteLine("rdfQuery: Parsed and Optimised Query with explicit nesting where appropriate:");
                            Console.WriteLine();
                            Console.WriteLine(q.ToString());
                            Console.WriteLine();
                            Console.WriteLine("rdfQuery: Algebra Form of Query");
                            Console.WriteLine();
                            Console.WriteLine(q.ToAlgebra().ToString());
                            break;
                        case "sparql":
                            Console.WriteLine(q.ToString());
                            break;
                        case "structure":
                            Console.WriteLine(q.ToAlgebra().ToString());
                            break;
                        default:
                            Console.Error.WriteLine("rdfQuery: Unknown dump format");
                            break;
                    }
                }
                else
                {
                    Console.Error.WriteLine("rdfQuery: Dry run complete - Query OK");
                }
                return;
            }

            //Show number of Graphs and Triples we're querying against
            if (!this._quiet) Console.Error.WriteLine("rdfQuery: Making query against " + this._store.Graphs.Count + " Graphs with " + this._store.Triples.Count() + " Triples (plus " + this._namedGraphs.Count + " named graphs which will be loaded as required)");

            //Now execute the actual query against the store
            //Add additional names graphs to the query
            foreach (String uri in this._namedGraphs)
            {
                try
                {
                    q.AddNamedGraph(new Uri(uri));
                }
                catch (UriFormatException)
                {
                    Console.Error.WriteLine("rdfQuery: Ignoring Named Graph URI '" + uri + "' since it does not appear to be a valid URI");
                }
            }
            try
            {
                //Object results = this._store.ExecuteQuery(q);
                var processor = new LeviathanQueryProcessor(_store);
                var results = processor.ProcessQuery(q);
                if (results is SparqlResultSet)
                {
                    this._resultsWriter.Save((SparqlResultSet)results, Console.Out);
                }
                else if (results is Graph)
                {
                    this._graphWriter.Save((Graph)results, Console.Out);
                }
                else
                {
                    Console.Error.WriteLine("rdfQuery: Unexpected result from query - unable to output result");
                }
            }
            catch (RdfQueryException queryEx)
            {
                Console.Error.WriteLine("rdfQuery: Query Error: Unable to execute query due to the following error:");
                Console.Error.WriteLine("rdfQuery: Query Error: " + queryEx.Message);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfQuery: Error: Unable to execute query due to the following error:");
                Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
            }
        }
Example #35
0
        public void SparqlQueryTimeoutMinimal()
        {
            Graph g = new Graph();
            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");

            String query = "SELECT * WHERE { ?s ?p ?o . ?x ?y ?z }";

            long currTimeout = Options.QueryExecutionTimeout;
            try
            {
                Options.QueryExecutionTimeout = 1;

                SparqlQuery q = this._parser.ParseFromString(query);
                q.PartialResultsOnTimeout = true;
                TripleStore store = new TripleStore();
                store.Add(g);

                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store);
                Object results = processor.ProcessQuery(q);
                if (results is SparqlResultSet)
                {
                    SparqlResultSet rset = (SparqlResultSet)results;
                    Console.WriteLine("Results: " + rset.Count + " - Query Time: " + q.QueryTime + "ms");
                    Assert.IsTrue(rset.Count < (g.Triples.Count * g.Triples.Count));
                }
                else
                {
                    Assert.Fail("Did not get a Result Set as expected");
                }
            }
            finally
            {
                Options.QueryExecutionTimeout = currTimeout;
            }
        }
Example #36
0
        public static void ResolveBGPsFromDB(ISparqlAlgebra algebra, IGraph g, Dictionary <string, string> dbURIs)
        {
            if (algebra is IBgp)
            {
                IBgp bgp = algebra as IBgp;
                //do work here

                /*
                 *  resolve DB name from subj/predicate/obj
                 *  resolve Table name
                 *  make query
                 *  convert results to rdf triples
                 *  add all the triples to IGraph g
                 */
                var triples = bgp.TriplePatterns;

                foreach (TriplePattern triple in triples)
                {
                    //do work here for each triple

                    string subjConnString = GetConnStringFromURI(dbURIs, triple.Subject.ToString());
                    string predConnString = GetConnStringFromURI(dbURIs, triple.Predicate.ToString());
                    string objConnString  = GetConnStringFromURI(dbURIs, triple.Object.ToString());

                    if (subjConnString == null && predConnString == null && objConnString == null)
                    {
                        //we deal with request to FEDERATED schema or it's an error
                        //if it's FEDERATED schema, we should find subclasses/subproperties, equivalent classes/properties and query for them

                        if (triple.Subject.VariableName == null) //is not a pattern
                        {
                            //IN FEDERATED schema there're no individuals, so we can't have subject URI or subject literal here!

                            //subject here could not be a URI! it would be logically incorrect!!!!!
                            //it could only be a pattern

                            throw new InvalidOperationException("Subject variable in tripple, referring to FEDERATED schema should be a PATTERN!");
                            //throw new NotImplementedException();
                        }
                        if (triple.Predicate.VariableName == null) //is not a pattern
                        {
                            //query for equivalent properties
                            TripleStore store = new TripleStore();
                            store.Add(g);

                            SparqlParameterizedString queryString = new SparqlParameterizedString();

                            queryString.Namespaces.AddNamespace("owl", new Uri("http://www.w3.org/2002/07/owl#"));
                            queryString.CommandText = @"SELECT ?property1 WHERE {
                                                        ?property owl:equivalentProperty ?property1
                                                        filter regex(str(?property), '^" + triple.Predicate.ToString().Trim('<', '>') + "')}";

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

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

                            //object can be a literal or a pattern
                            foreach (SparqlResult resultPredicate in results)
                            {
                                //query with new predicates and transform the results to FEDERATED schema syntax
                                queryString             = new SparqlParameterizedString();
                                queryString.CommandText = $"SELECT * WHERE {{ ?subj <{resultPredicate[0].ToString()}> {triple.Object.ToString()} }} ";
                                SparqlResultSet resultSet = QuerySparqlFromDB(g, queryString, dbURIs);

                                string federatedStem = triple.Predicate.ToString().Trim('<', '>').Split('#')[0]; //left part (before '#') -> /FEDERATED/table name
                                //federatedStem += '/'; // /FEDERATED/table name/

                                foreach (SparqlResult result in resultSet)
                                {
                                    Dictionary <string, string> dbInfo = GetDatabaseInfoForIndividualURI(result[0].ToString());
                                    string subjStr = $"{federatedStem}/{dbInfo["dbName"]}.{dbInfo["columnName"]}.{dbInfo["columnValue"]}";
                                    string predStr = triple.Predicate.ToString().Trim('<', '>');
                                    string objStr;
                                    if (triple.Object.VariableName == null) //not a pattern
                                    {
                                        objStr = triple.Object.ToString().Trim('"');
                                    }
                                    else //object was a pattern ?object in sparql query
                                    {
                                        //dbInfo = GetDatabaseInfoForIndividualURI(result[1].ToString());
                                        if (IsLiteralValue(result[1].ToString()))
                                        {
                                            objStr = result[1].ToString();
                                        }
                                        else
                                        {
                                            dbInfo = GetDatabaseInfoForIndividualURI(result[1].ToString());
                                            objStr = $"{federatedStem}/{dbInfo["dbName"]}.{dbInfo["columnName"]}.{dbInfo["columnValue"]}";
                                        }
                                    }
                                    INode subj = g.CreateUriNode(new Uri(subjStr));
                                    INode pred = g.CreateUriNode(new Uri(predStr));
                                    INode obj; // = g.CreateLiteralNode($"{rawTriple.Obj}");
                                    if (IsLiteralValue(objStr))
                                    {
                                        obj = g.CreateLiteralNode(objStr);
                                    }
                                    else
                                    {
                                        obj = g.CreateUriNode(new Uri(objStr));
                                    }
                                    g.Assert(new Triple(subj, pred, obj));
                                }
                            }


                            //throw new NotImplementedException();
                        }
                        if (triple.Object.VariableName == null) //is not a pattern
                        {
                            if (!IsLiteralValue(triple.Object.ToString()))
                            {
                                throw new InvalidOperationException("Object variable in tripple, referring to FEDERATED schema should be a PATTERN!");
                                //throw new NotImplementedException();
                            }
                        }
                        //throw new NotImplementedException();
                    }

                    if (subjConnString != null) //most probably, subjectConnString will be NULL (cause subject may be a pattern)
                    {
                        //TODO
                        //if subj is not a literal, we should query DB for subj triples!!!
                        //<http://www.semanticweb.org/LMS/User/ID.1> <http://www.semanticweb.org/LMS/User#NAME> ?name

                        //<subject> <predicate> ?object

                        /*
                         *  SELECT User.NAME
                         *  FROM table(subject)
                         *  WHERE User.ID=1 AND User.NAME IS NOT NULL
                         */

                        //<subject> ?predicate ?object

                        /*
                         *  SELECT *
                         *  FROM table(subject)
                         *  WHERE User.ID=1
                         */

                        //<subject> ?predicate "Object"

                        /*
                         *  SELECT *
                         *  FROM table(subject)
                         *  WHERE User.ID=1
                         *  //check for "Object" inside DataReader, when queried
                         */

                        DBLoader dbLoader = new DBLoader(subjConnString);
                        Dictionary <string, string> dbInfo = GetDatabaseInfoForIndividualURI(triple.Subject.ToString());

                        List <RawTriple> rawTriples = dbLoader.GetTriplesForSubject(
                            tableName: dbInfo["tableName"],
                            individualColName: dbInfo["columnName"],
                            individualColValue: dbInfo["columnValue"],
                            prefixURI: dbInfo["prefix"],
                            predicateColName: triple.Predicate.VariableName == null ? GetPrefixDbNameTableNameColNameFromURI(triple.Predicate.ToString())["columnName"] : null,
                            obj: triple.Object.VariableName == null ? triple.Object.ToString().Trim('>', '<') : null
                            );
                        foreach (var rawTriple in rawTriples)
                        {
                            INode subj = g.CreateUriNode(new Uri(rawTriple.Subj));
                            INode pred = g.CreateUriNode(new Uri(rawTriple.Pred));
                            INode obj  = g.CreateLiteralNode($"{rawTriple.Obj}");
                            g.Assert(new Triple(subj, pred, obj));
                        }
                    }
                    if (predConnString != null)
                    {
                        //referring to DataType- or Object- Property
                        if (triple.Object.VariableName == null) //object is not a pattern
                        {
                            if (IsLiteralValue(triple.Object.ToString()))
                            {
                                // ?s <predicate> "Object"

                                /*
                                 *  SELECT *
                                 *  FROM table(predicate)
                                 *  WHERE table.Attribute="Object"
                                 */
                                DBLoader dbLoader = new DBLoader(predConnString);
                                Dictionary <string, string> dbInfo     = GetPrefixDbNameTableNameColNameFromURI(triple.Predicate.ToString());
                                List <RawTriple>            rawTriples = dbLoader.GetTriplesForPredicateObject(
                                    tableName: dbInfo["tableName"],
                                    columnName: dbInfo["columnName"],
                                    prefixURI: dbInfo["prefix"],
                                    obj: triple.Object.ToString());
                                foreach (var rawTriple in rawTriples)
                                {
                                    INode subj = g.CreateUriNode(new Uri(rawTriple.Subj));
                                    INode pred = g.CreateUriNode(new Uri(rawTriple.Pred));
                                    INode obj  = g.CreateLiteralNode($"{rawTriple.Obj}");
                                    g.Assert(new Triple(subj, pred, obj));
                                }
                            }
                            else if (objConnString != null)
                            {
                                // ?s <predicate> <object>
                                throw new NotImplementedException();
                            }
                        }
                        else //object is a pattern
                        {
                            //?s <predicate> ?object

                            /*
                             *  SELECT *
                             *  FROM table(predicate)
                             *  WHERE table.Attribute="Object"
                             */
                            DBLoader dbLoader = new DBLoader(predConnString);
                            Dictionary <string, string> dbInfo     = GetPrefixDbNameTableNameColNameFromURI(triple.Predicate.ToString());
                            List <RawTriple>            rawTriples = dbLoader.GetTriplesForPredicateObject(
                                tableName: dbInfo["tableName"],
                                columnName: dbInfo["columnName"],
                                prefixURI: dbInfo["prefix"],
                                obj: null);
                            foreach (var rawTriple in rawTriples)
                            {
                                INode subj = g.CreateUriNode(new Uri(rawTriple.Subj));
                                INode pred = g.CreateUriNode(new Uri(rawTriple.Pred));
                                INode obj  = g.CreateLiteralNode($"{rawTriple.Obj}");
                                g.Assert(new Triple(subj, pred, obj));
                            }
                        }
                    }
                    if (objConnString != null) //object is not a pattern
                    {
                        //TODO
                        throw new NotImplementedException();
                    }

                    //check if subj, pred and obj refer to one DB
                }
            }
            else
            {
                if (algebra is IUnaryOperator)
                {
                    algebra = algebra as IUnaryOperator;
                    ResolveBGPsFromDB((algebra as IUnaryOperator).InnerAlgebra, g, dbURIs);
                }
                else if (algebra is IAbstractJoin)
                {
                    ResolveBGPsFromDB((algebra as IAbstractJoin).Lhs, g, dbURIs);
                    ResolveBGPsFromDB((algebra as IAbstractJoin).Rhs, g, dbURIs);
                }
            }
        }
    protected void Button2_Click1(object sender, EventArgs e)
    {
        TripleStore store = new TripleStore();
        Graph       g1    = new Graph();

        g1.LoadFromFile(Server.MapPath("SVUModeling.rdf"));
        store.Add(g1);
        Label1.Text       = "Economic Program Details";
        Label1.Visible    = true;
        GridView1.Visible = false;
        InMemoryDataset ds = new InMemoryDataset(store);
        //Get the Query processor
        ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);

        //Use the SparqlQueryParser to give us a SparqlQuery object
        //Should get a Graph back from a CONSTRUCT query
        Label2.Text    = "Economic Director Informations ";
        Label2.Visible = true;
        // to select the Economic Director Informations
        SparqlQueryParser sparqlparser = new SparqlQueryParser();
        SparqlQuery       query        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                SELECT   ?EconomicDirectorInfo 
                WHERE {
                ?t   owl:EconomicDirectorInfoProperty ?EconomicDirectorInfo
                }");
        Object            results      = processor.ProcessQuery(query);
        DataTable         DT2          = new DataTable();
        SparqlResultSet   rset         = (SparqlResultSet)results;

        DT2 = FillDataTable(rset);
        GridView2.DataSource = DT2;
        GridView2.DataBind();
        GridView2.Visible = true;
        //to retrival the Teachers Economic program
        Label3.Text    = "Teachers Of Economic Program";
        Label3.Visible = true;
        SparqlQueryParser sparqlparser2 = new SparqlQueryParser();
        SparqlQuery       query2        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?TeachersEconomic 
                WHERE {
                ?t   owl:TeachersOfEconomic ?TeachersEconomic 
                }");
        Object            results2      = processor.ProcessQuery(query2);
        DataTable         DT3           = new DataTable();
        SparqlResultSet   rset5         = (SparqlResultSet)results2;

        DT3 = FillDataTable(rset5);
        GridView3.DataSource = DT3;
        GridView3.DataBind();
        GridView3.Visible = true;
        //to select Courses Of Economic
        Label4.Text    = "Courses of Economic Program";
        Label4.Visible = true;
        SparqlQueryParser sparqlparser4 = new SparqlQueryParser();
        SparqlQuery       query4        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?CoursesEconomic 
                WHERE {
                ?t   owl:CoursesOfEconomic ?CoursesEconomic 
                }");
        Object            results4      = processor.ProcessQuery(query4);
        DataTable         DT4           = new DataTable();
        SparqlResultSet   rset6         = (SparqlResultSet)results4;

        DT4 = FillDataTable(rset6);
        GridView4.DataSource = DT4;
        GridView4.DataBind();
        GridView4.Visible = true;
    }
Example #38
0
        private void TestBindings(ISparqlDataset data, String queryWithBindings)
        {
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(data);
            SparqlQuery bindingsQuery = this._parser.ParseFromString(queryWithBindings);

            SparqlResultSet bindingsResults = processor.ProcessQuery(bindingsQuery) as SparqlResultSet;

            if (bindingsResults == null) Assert.Fail("Did not get a SPARQL Result Set for the Bindings Query");

            Console.WriteLine("Bindings Results");
            TestTools.ShowResults(bindingsResults);
            Console.WriteLine();

            Assert.IsTrue(bindingsResults.IsEmpty, "Result Set should be empty");
        }
        private bool test1()
        {
            Notation3Parser n3parser = new Notation3Parser();

            try
            {
                //Load using Filename
                n3parser.Load(g, "szepmuveszeti.n3");
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
                return(false);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }

            TripleStore ts = new TripleStore();

            ts.Add(g);

            //Get the Query processor
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(ts);

            try
            {
                SparqlQuery q       = new SparqlQueryParser().ParseFromString("PREFIX ecrm:<http://erlangen-crm.org/current/> SELECT ?actor {?actor a ecrm:E39_Actor}");
                Object      results = processor.ProcessQuery(q);
                Console.WriteLine("First 5 actor:");
                if (results is SparqlResultSet)
                {
                    SparqlResultSet rset = (SparqlResultSet)results;
                    for (int idx = 0; idx < 5; ++idx)
                    {
                        Console.WriteLine(rset.Results[idx]);
                    }
                }



                Console.WriteLine("Delete the first actor:");
                SparqlUpdateCommandSet delete = new SparqlUpdateParser().ParseFromString("PREFIX ecrm:<http://erlangen-crm.org/current/> DELETE {<http://data.szepmuveszeti.hu/id/collections/museum/E39_Actor/f5f86cb4-b308-34b9-a73b-d40d474d735d> a ecrm:E39_Actor}WHERE{}");
                var updateProcessor           = new LeviathanUpdateProcessor(ts);
                updateProcessor.ProcessCommandSet(delete);
                var result2 = processor.ProcessQuery(q);
                if (result2 is SparqlResultSet)
                {
                    SparqlResultSet rset = (SparqlResultSet)result2;
                    for (int idx = 0; idx < 5; ++idx)
                    {
                        Console.WriteLine(rset.Results[idx]);
                    }
                }



                SparqlUpdateCommandSet insert = new SparqlUpdateParser().ParseFromString("PREFIX ecrm:<http://erlangen-crm.org/current/> INSERT {<http://data.szepmuveszeti.hu/id/collections/museum/E39_Actor/f5f86cb4-b308-34b9-a73b-d40d474d735d> a ecrm:E39_Actor}WHERE{}");
                updateProcessor = new LeviathanUpdateProcessor(ts);
                updateProcessor.ProcessCommandSet(insert);
                var result3 = processor.ProcessQuery(q);
                Console.WriteLine("Insert the first actor:");
                if (result3 is SparqlResultSet)
                {
                    SparqlResultSet rset = (SparqlResultSet)result3;
                    for (int idx = 0; idx < 5; ++idx)
                    {
                        Console.WriteLine(rset.Results[idx]);
                    }
                }
            }
            catch (Exception e)
            {
                return(false);
            }



            return(true);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text    = "there is three types of programs at Syrian Virtual University";
        Label1.Visible = true;
        Graph g1 = new Graph();

        g1.LoadFromFile(Server.MapPath("SVUModeling.rdf"));
        TripleStore store = new TripleStore();

        store.Add(g1);
        //Assume that we fill our Store with data from somewhere

        //Create a dataset for our queries to operate over
        //We need to explicitly state our default graph or the unnamed graph is used
        //Alternatively you can set the second parameter to true to use the union of all graphs
        //as the default graph
        InMemoryDataset ds = new InMemoryDataset(store);

        //Get the Query processor
        ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);

        //Use the SparqlQueryParser to give us a SparqlQuery object
        //Should get a Graph back from a CONSTRUCT query
        SparqlQueryParser sparqlparser = new SparqlQueryParser();
        SparqlQuery       query        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                                                           prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                                                           prefix owl: <http://www.w3.org/2002/07/owl#>
                                                           SELECT   ?ProgramName 
                                                           WHERE {
                                                           ?t   owl:StudyingAtSVU ?ProgramName 
                                                        }");
        Object            results      = processor.ProcessQuery(query);
        DataTable         DT1          = new DataTable();
        SparqlResultSet   rset         = (SparqlResultSet)results;

        DT1 = FillDataTable(rset);
        GridView1.DataSource = DT1;
        GridView1.DataBind();
        GridView1.Visible = true;


        // to select Bachelor Programs
        Label2.Text    = "Bachelor Programs At SVU";
        Label2.Visible = true;
        SparqlQueryParser sparqlparser2 = new SparqlQueryParser();
        SparqlQuery       query2        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                 prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                 prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT ?BachelorPrograms
                WHERE {
                ?t   owl:BachelorProgramAtSVU ?BachelorPrograms
                }");
        Object            results2      = processor.ProcessQuery(query2);
        DataTable         DT2           = new DataTable();
        SparqlResultSet   rset2         = (SparqlResultSet)results2;

        DT2 = FillDataTable(rset2);
        GridView2.DataSource = DT2;
        GridView2.DataBind();
        GridView2.Visible = true;

        // to select Master Programs
        Label3.Text    = "Master Programs At SVU";
        Label3.Visible = true;
        SparqlQueryParser sparqlparser3 = new SparqlQueryParser();
        SparqlQuery       query3        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT ?MasterPrograms 
                WHERE {
                ?t   owl:MasterProgramAtSVU ?MasterPrograms 
                }");
        Object            results3      = processor.ProcessQuery(query3);
        DataTable         DT3           = new DataTable();
        SparqlResultSet   rset3         = (SparqlResultSet)results3;

        DT3 = FillDataTable(rset3);
        GridView3.DataSource = DT3;
        GridView3.DataBind();
        GridView3.Visible = true;

        // to select Training Programs
        Label4.Text    = "Training Programs At SVU";
        Label4.Visible = true;
        SparqlQueryParser sparqlparser4 = new SparqlQueryParser();
        SparqlQuery       query4        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?TrainingPrograms 
                WHERE {
                ?t   owl:TrainingProgramAtSVU ?TrainingPrograms 
                }");
        Object            results4      = processor.ProcessQuery(query4);
        DataTable         DT4           = new DataTable();
        SparqlResultSet   rset4         = (SparqlResultSet)results4;

        DT4 = FillDataTable(rset4);
        GridView4.DataSource = DT4;
        GridView4.DataBind();
        GridView4.Visible = true;
    }
Example #41
0
        private void TestNegation(ISparqlDataset data, String queryWithNegation, String queryWithoutNegation)
        {
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(data);
            SparqlQuery negQuery = this._parser.ParseFromString(queryWithNegation);
            SparqlQuery noNegQuery = this._parser.ParseFromString(queryWithoutNegation);

            SparqlResultSet negResults = processor.ProcessQuery(negQuery) as SparqlResultSet;
            SparqlResultSet noNegResults = processor.ProcessQuery(noNegQuery) as SparqlResultSet;

            if (negResults == null) Assert.Fail("Did not get a SPARQL Result Set for the Negation Query");
            if (noNegResults == null) Assert.Fail("Did not get a SPARQL Result Set for the Non-Negation Query");

            Console.WriteLine("Negation Results");
            TestTools.ShowResults(negResults);
            Console.WriteLine();
            Console.WriteLine("Non-Negation Results");
            TestTools.ShowResults(noNegResults);
            Console.WriteLine();

            Assert.AreEqual(noNegResults, negResults, "Result Sets should have been equal");
        }
    protected void Button11_Click(object sender, EventArgs e)
    {
        //Bachelor in Communications Technology Program Details
        TripleStore store = new TripleStore();
        Graph       g1    = new Graph();

        g1.LoadFromFile(Server.MapPath("SVUModeling.rdf"));
        store.Add(g1);
        InMemoryDataset ds = new InMemoryDataset(store);
        //Get the Query processor
        ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);

        Label1.Text       = "Bachelor in Communications Technology Program : BACT Details";
        Label1.Visible    = true;
        GridView1.Visible = false;
        Label2.Text       = "Bachelor in Communications Technology Program Informations ";
        Label2.Visible    = true;
        // to select the Communications Technology program's Director Informations
        SparqlQueryParser sparqlparser = new SparqlQueryParser();
        SparqlQuery       query        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                SELECT   ?BACTDirectorInfo
                WHERE {
                ?t   owl:TelecommunicationsTechnologyDirectorInfoProperty ?BACTDirectorInfo
                }");
        Object            results      = processor.ProcessQuery(query);
        DataTable         DT2          = new DataTable();
        SparqlResultSet   rset         = (SparqlResultSet)results;

        DT2 = FillDataTable(rset);
        GridView2.DataSource = DT2;
        GridView2.DataBind();
        GridView2.Visible = true;
        //to retrival the Teachers of Bachelor in Communications Technology program
        Label3.Text    = "Teachers Of Bachelor in Communications Technology Program";
        Label3.Visible = true;
        SparqlQueryParser sparqlparser3 = new SparqlQueryParser();
        SparqlQuery       query3        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?BACTTeachers
                WHERE {
                ?t   owl:TeachersOfTelecommunicationsTechnology ?BACTTeachers
                }");
        Object            results3      = processor.ProcessQuery(query3);
        DataTable         DT3           = new DataTable();
        SparqlResultSet   rset3         = (SparqlResultSet)results3;

        DT3 = FillDataTable(rset3);
        GridView3.DataSource = DT3;
        GridView3.DataBind();
        GridView3.Visible = true;
        //to select Courses Of Bachelor in Communications Technology
        Label4.Text    = "Courses of Bachelor in Communications Technology Program";
        Label4.Visible = true;
        SparqlQueryParser sparqlparser4 = new SparqlQueryParser();
        SparqlQuery       query4        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?BACTCourses
                WHERE {
                ?t   owl:CoursesOfTelecommunicationsTechnology ?BACTCourses
                }");
        Object            results4      = processor.ProcessQuery(query4);
        DataTable         DT4           = new DataTable();
        SparqlResultSet   rset4         = (SparqlResultSet)results4;

        DT4 = FillDataTable(rset4);
        GridView4.DataSource = DT4;
        GridView4.DataBind();
        GridView4.Visible = true;
    }
Example #43
0
        private void TestNegation(ISparqlDataset data, String queryWithNegation)
        {
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(data);
            SparqlQuery negQuery = this._parser.ParseFromString(queryWithNegation);

            SparqlResultSet negResults = processor.ProcessQuery(negQuery) as SparqlResultSet;

            if (negResults == null) Assert.Fail("Did not get a SPARQL Result Set for the Negation Query");

            Console.WriteLine("Negation Results");
            TestTools.ShowResults(negResults);
            Console.WriteLine();

            Assert.IsTrue(negResults.IsEmpty, "Result Set should be empty");
        }
        public PartialViewResult ExecuteQuery(Query data)
        {
            ResultSet _ResultSet = new ResultSet();

            SparqlResultSet _SparqlResultSet = null;
            //string query = Request.Unvalidated["SparqlQuery"];
            // Create a Triple Collection with only a subject index
            BaseTripleCollection tripleCollection = new TreeIndexedTripleCollection(
                true, false, false, false, false, false, MultiDictionaryMode.AVL);
            // Create a Graph using the customized triple collection
            //  Graph g = new Graph(tripleCollection);
            TripleStore _TripleStore = new TripleStore();
            string      _OwlFileName = GetAttachedOwlFile();

            if (!_OwlFileName.Equals("Error"))
            {
                string _OWLFilePath = Server.MapPath("~/DataSets/" + _OwlFileName);
                _TripleStore.LoadFromFile(_OWLFilePath);
                ISparqlDataset          _ISparqlDataset          = new InMemoryDataset(_TripleStore);
                LeviathanQueryProcessor _LeviathanQueryProcessor = new LeviathanQueryProcessor(_ISparqlDataset);
                SparqlQueryParser       _SparqlQueryParser       = new SparqlQueryParser();
                //  Then we can parse a SPARQL string into a query
                if (ModelState.IsValid)
                {
                    try {
                        SparqlQuery _SparqlQuery = _SparqlQueryParser.ParseFromString(data.query);
                        var         results      = _LeviathanQueryProcessor.ProcessQuery(_SparqlQuery);
                        _SparqlResultSet = (SparqlResultSet)results;

                        ///
                        _ResultSet.Columns = _SparqlResultSet.Variables;
                        string value = null;
                        foreach (SparqlResult _SparqlResult in _SparqlResultSet)
                        {
                            foreach (var _Col in _ResultSet.Columns)
                            {
                                INode _Node;
                                if (_SparqlResult.TryGetValue(_Col, out _Node))
                                {
                                    switch (_Node.NodeType)
                                    {
                                    case NodeType.Uri:
                                        value = ((IUriNode)_Node).Uri.AbsoluteUri;
                                        break;

                                    case NodeType.Literal:

                                        value = ((ILiteralNode)_Node).Value;
                                        break;

                                    default:
                                        Console.WriteLine("Error Node");
                                        ModelState.AddModelError("", "Error in The Node Type ");
                                        break;
                                    }
                                }
                                else
                                {
                                    value = String.Empty;
                                }
                                //Data To Rows
                                _ResultSet.Rows.Enqueue(value);
                            }
                        }

                        ///
                    }
                    catch (RdfParseException e)
                    {
                        //  Console.SetError(e.ToString());
                        ModelState.AddModelError("", "Error in The Syntax " + e.Message);
                        TempData["message"] = string.Format("Syntaxerror");
                    }
                }
                else
                {
                    TempData["message"] = string.Format("EmptyQuery");
                }
            }
            else
            {
                TempData["message"] = string.Format("ChooseDb");
            }
            return(PartialView("_ExecuteQuery", _ResultSet));
        }
Example #45
0
        private void TestProductTimeout(IGraph data, String query, bool useGlobal, int expectedResults)
        {
            Console.WriteLine("Maximum Expected Results: " + expectedResults);
            Console.WriteLine("Initial Global Timeout: " + Options.QueryExecutionTimeout);
            Console.WriteLine();

            long globalOrig = Options.QueryExecutionTimeout;
            try
            {
                if (useGlobal)
                {
                    Console.WriteLine("Global Timeout setting in use");
                }
                else
                {
                    Console.WriteLine("Per Query Timeout setting in use");
                }
                Console.WriteLine();

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

                SparqlQuery q = this._parser.ParseFromString(query);
                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store);

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

                //Evaluate for each Timeout
                foreach (long t in this._timeouts)
                {
                    //Set the Timeout and ask for Partial Results
                    if (useGlobal)
                    {
                        Options.QueryExecutionTimeout = t;
                    }
                    else
                    {
                        q.Timeout = t;
                    }
                    q.PartialResultsOnTimeout = true;

                    //Check that the reported Timeout matches the expected
                    SparqlEvaluationContext context = new SparqlEvaluationContext(q, null);
                    long expected;
                    if (useGlobal)
                    {
                        expected = t;
                    }
                    else
                    {
                        if (Options.QueryExecutionTimeout > 0 && t <= Options.QueryExecutionTimeout)
                        {
                            expected = t;
                        }
                        else if (Options.QueryExecutionTimeout == 0)
                        {
                            expected = t;
                        }
                        else
                        {
                            expected = Options.QueryExecutionTimeout;
                        }
                    }
                    Assert.AreEqual(expected, context.QueryTimeout, "Reported Timeout not as expected");

                    //Run the Query
                    Object results = processor.ProcessQuery(q);
                    if (results is SparqlResultSet)
                    {
                        SparqlResultSet rset = (SparqlResultSet)results;

                        Console.WriteLine("Requested Timeout: " + t + " - Actual Timeout: " + expected + "ms - Results: " + rset.Count + " - Query Time: " + q.QueryTime + "ms");
                        Assert.IsTrue(rset.Count <= expectedResults, "Results should be <= expected");
                    }
                    else
                    {
                        Assert.Fail("Did not get a Result Set as expected");
                    }
                }
            }
            finally
            {
                Options.QueryExecutionTimeout = globalOrig;
            }
        }
Example #46
0
        public void SparqlQueryTimeoutDuringProductLazy2()
        {
            String query = "ASK WHERE { ?s ?p ?o . ?x ?y ?z }";
            SparqlQuery q = this._parser.ParseFromString(query);
            q.Timeout = 1;

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            store.Add(g);
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store);
            try
            {
                processor.ProcessQuery(q);
                Assert.Fail("Did not throw a RdfQueryTimeoutException as expected");
            }
            catch (RdfQueryTimeoutException timeoutEx)
            {
                TestTools.ReportError("Timeout", timeoutEx, false);

                Console.WriteLine();
                Console.WriteLine("Execution Time: " + q.QueryExecutionTime.Value.ToString());
            }
        }
        private int ProcessEvaluationTest(SparqlQueryParser parser, Triple commentDef, String queryFile, String dataFile, List <String> dataFiles, String resultFile)
        {
            Console.WriteLine("# Processing Evaluation Test " + Path.GetFileName(queryFile));

            if (commentDef != null)
            {
                Console.WriteLine(commentDef.Object.ToString());
                Console.WriteLine();
            }

            if (dataFiles.Contains(dataFile))
            {
                dataFiles.Remove(dataFile);
            }
            if (queryFile.StartsWith("file:///"))
            {
                queryFile = queryFile.Substring(8);
            }
            if (dataFile != null && dataFile.StartsWith("file:///"))
            {
                dataFile = dataFile.Substring(8);
            }
            if (resultFile.StartsWith("file:///"))
            {
                resultFile = resultFile.Substring(8);
            }

            Console.WriteLine("Query File is " + queryFile);
            if (evaluationTestOverride.Any(x => queryFile.EndsWith(x)))
            {
                Console.WriteLine();
                Console.WriteLine("# Test Result = Manually overridden to Pass (Test Passed)");
                testsPassed++;
                testsEvaluationPassed++;
                return(1);
            }
            if (dataFile != null)
            {
                Console.WriteLine("Default Graph File is " + dataFile);
            }
            foreach (String file in dataFiles)
            {
                Console.WriteLine("Uses Named Graph File " + file);
            }
            Console.WriteLine("Expected Result File is " + resultFile);
            Console.WriteLine();

            SparqlQuery query;

            try
            {
                query = parser.ParseFromFile(queryFile);

                Console.WriteLine(query.ToString());
                Console.WriteLine();
                Console.WriteLine("Formatted with SparqlFormatter");
                SparqlFormatter formatter = new SparqlFormatter(query.NamespaceMap);
                Console.WriteLine(formatter.Format(query));
                Console.WriteLine();

                try
                {
                    Console.WriteLine(query.ToAlgebra().ToString());
                    Console.WriteLine();
                }
                catch
                {
                    //Do Nothing
                }
            }
            catch (RdfParseException parseEx)
            {
                this.ReportError("Query Parser Error", parseEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result = Unable to parse query (Test Failed)");
                return(-1);
            }

            IInMemoryQueryableStore store;

            if (dataFile != null)
            {
                store = new TripleStore();
            }
            else
            {
                store = new WebDemandTripleStore();
            }

            //Load Default Graph
            Graph defaultGraph = new Graph();

            try
            {
                if (dataFile != null)
                {
                    FileLoader.Load(defaultGraph, dataFile);
                }
                store.Add(defaultGraph);
            }
            catch (RdfParseException parseEx)
            {
                this.ReportError("Parser Error", parseEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result = Unable to parse Default Graph (Test Failed)");
                return(-1);
            }

            //Load Named Graphs
            try
            {
                foreach (String graphFile in dataFiles)
                {
                    Graph namedGraph = new Graph();
                    if (graphFile.StartsWith("file:///"))
                    {
                        FileLoader.Load(namedGraph, graphFile.Substring(8));
                    }
                    else
                    {
                        FileLoader.Load(namedGraph, graphFile);
                    }
                    store.Add(namedGraph);
                }
            }
            catch (RdfParseException parseEx)
            {
                this.ReportError("Parser Error", parseEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Unable to parse Named Graph (Test Failed)");
                return(-1);
            }

            //Create a Dataset and then Set Graphs
            //ISparqlDataset dataset = new InMemoryQuadDataset(store);
            ISparqlDataset dataset = new InMemoryDataset(store);

            if (!query.DefaultGraphs.Any())
            {
                query.AddDefaultGraph(defaultGraph.BaseUri);
            }
            if (!query.NamedGraphs.Any())
            {
                foreach (String namedGraphUri in dataFiles)
                {
                    query.AddNamedGraph(new Uri(namedGraphUri));
                }
            }

            //Try and get the result
            Object results = null;

            try
            {
                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset);
                results = processor.ProcessQuery(query);
            }
            catch (RdfQueryException queryEx)
            {
                this.ReportError("Query Error", queryEx);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Query execution failed (Test Failed)");
                return(-1);
            }
            catch (Exception ex)
            {
                this.ReportError("Other Error", ex);
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Query failed (Test Failed)");
                return(-1);
            }

            if (results == null)
            {
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - No result was returned from the Query (Test Failed)");
                return(-1);
            }

            //Load in the expected results
            if (results is SparqlResultSet)
            {
                //Save our Results so we can manually compare as needed
                SparqlResultSet ourResults = (SparqlResultSet)results;
                SparqlXmlWriter writer     = new SparqlXmlWriter();
                writer.Save(ourResults, resultFile + ".out");
                SparqlResultSet expectedResults = new SparqlResultSet();

                if (resultFile.EndsWith(".srx"))
                {
                    try
                    {
                        SparqlXmlParser resultSetParser = new SparqlXmlParser();
                        resultSetParser.Load(expectedResults, resultFile);
                    }
                    catch (RdfParseException parseEx)
                    {
                        this.ReportError("Result Set Parser Error", parseEx);
                        testsIndeterminate++;
                        testsEvaluationIndeterminate++;
                        Console.WriteLine("# Test Result - Error loading expected Result Set (Test Indeterminate)");
                        return(0);
                    }
                }
                else if (resultFile.EndsWith(".ttl") || resultFile.EndsWith(".rdf"))
                {
                    try
                    {
                        SparqlRdfParser resultSetParser = new SparqlRdfParser();
                        resultSetParser.Load(expectedResults, resultFile);
                    }
                    catch (RdfParseException parseEx)
                    {
                        this.ReportError("Result Set Parser Error", parseEx);
                        testsIndeterminate++;
                        testsEvaluationIndeterminate++;
                        Console.WriteLine("# Test Result - Error loading expected Result Set (Test Indeterminate)");
                        return(0);
                    }
                }
                else
                {
                    testsIndeterminate++;
                    testsEvaluationIndeterminate++;
                    Console.WriteLine("# Test Result - Unable to load the expected Result Set (Test Indeterminate)");
                    return(0);
                }

                try
                {
                    ourResults.Trim();
                    expectedResults.Trim();
                    if (ourResults.Equals(expectedResults))
                    {
                        testsPassed++;
                        testsEvaluationPassed++;
                        Console.WriteLine("# Test Result - Result Set as expected (Test Passed)");
                        return(1);
                    }
                    else
                    {
                        Console.WriteLine("Final Query");
                        Console.WriteLine(query.ToString());
                        Console.WriteLine();
                        this.ShowTestData(store);
                        this.ShowResultSets(ourResults, expectedResults);
                        testsFailed++;
                        testsEvaluationFailed++;
                        Console.WriteLine("# Test Result - Result Set not as expected (Test Failed)");
                        return(-1);
                    }
                }
                catch (NotImplementedException)
                {
                    this.ShowResultSets(ourResults, expectedResults);
                    testsIndeterminate++;
                    testsEvaluationIndeterminate++;
                    Console.WriteLine("# Test Result - Unable to establish if Result Set was as expected (Test Indeterminate)");
                    return(0);
                }
            }
            else if (results is Graph)
            {
                if (resultFile.EndsWith(".ttl"))
                {
                    //Save our Results so we can manually compare as needed
                    Graph ourResults = (Graph)results;
                    CompressingTurtleWriter writer = new CompressingTurtleWriter();
                    writer.Save(ourResults, resultFile + ".out");

                    try
                    {
                        Graph        expectedResults = new Graph();
                        TurtleParser ttlparser       = new TurtleParser();
                        ttlparser.Load(expectedResults, resultFile);

                        try
                        {
                            if (ourResults.Equals(expectedResults))
                            {
                                testsPassed++;
                                testsEvaluationPassed++;
                                Console.WriteLine("# Test Result - Graph as expected (Test Passed)");
                                return(1);
                            }
                            else
                            {
                                this.ShowTestData(store);
                                this.ShowGraphs(ourResults, expectedResults);
                                testsFailed++;
                                testsEvaluationFailed++;
                                Console.WriteLine("# Test Result - Graph not as expected (Test Failed)");
                                return(-1);
                            }
                        }
                        catch (NotImplementedException)
                        {
                            this.ShowGraphs(ourResults, expectedResults);
                            testsIndeterminate++;
                            testsEvaluationIndeterminate++;
                            Console.WriteLine("# Test Result - Unable to establish if Graph was as expected (Test Indeterminate)");
                            return(0);
                        }
                    }
                    catch (RdfParseException parseEx)
                    {
                        this.ReportError("Graph Parser Error", parseEx);
                        testsIndeterminate++;
                        testsEvaluationIndeterminate++;
                        Console.WriteLine("# Test Result - Error loading expected Graph (Test Indeterminate)");
                        return(0);
                    }
                }
                else
                {
                    testsIndeterminate++;
                    testsEvaluationIndeterminate++;
                    Console.WriteLine("# Test Result - Unable to load expected Graph (Test Indeterminate)");
                    return(0);
                }
            }
            else
            {
                testsFailed++;
                testsEvaluationFailed++;
                Console.WriteLine("# Test Result - Didn't produce a Graph as expected (Test Failed)");
                return(-1);
            }
        }