public string QueryTripleStoreRaw(SparqlParameterizedString queryString)
        {
            var sparqlParser = new SparqlQueryParser();

            AddAllColidNamespaces(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 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.True(false, "Should have errored");
            }
            catch (RdfQueryException queryEx)
            {
                Console.WriteLine("Errored as expected");
                TestTools.ReportError("Query Error", queryEx);
            }
        }
Esempio n. 3
0
        public void TestAsyncQueryWithQueryCallback()
        {
            var store = new TripleStore();
            var g     = new Graph();

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

            var processor = new LeviathanQueryProcessor(dataset);

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

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

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

            Assert.True(callbackInvoked);
            Assert.True(resultCount > 0);
            Assert.Equal(syncResultCount, resultCount);
        }
Esempio n. 4
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);
        }
Esempio n. 5
0
        public static AmrTerm GetAmrTerm(IGraph g, AmrNode node)
        {
            AmrTerm           result  = new AmrTerm();
            SparqlQueryParser qparser = new SparqlQueryParser();
            var         str           = "SELECT ?p WHERE { <" + node.uriid + ">  <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?p }";
            SparqlQuery q             = qparser.ParseFromString(str);
            var         rset          = (SparqlResultSet)g.ExecuteQuery(q);
            var         SB            = new StringBuilder();

            if (rset.Result && rset.Results.Count > 0)
            {
                foreach (var set in rset.Results)
                {
                    foreach (var r in set)
                    {
                        result.uriid = r.Value.ToString();
                    }
                }
            }
            qparser = new SparqlQueryParser();
            str     = "SELECT ?p WHERE { <" + result.uriid + ">  <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?p }";
            q       = qparser.ParseFromString(str);
            rset    = (SparqlResultSet)g.ExecuteQuery(q);

            if (rset.Result && rset.Results.Count > 0)
            {
                foreach (var set in rset.Results)
                {
                    foreach (var r in set)
                    {
                        result.type = r.Value.ToString();
                    }
                }
            }


            //s http://amr.isi.edu/frames/ld/v1.2.2/dedicate-01
            //x http://www.w3.org/1999/02/22-rdf-syntax-ns#type
            //p http://amr.isi.edu/rdf/core-amr#Frame

            return(result);
        }
        public IGraph QueryTripleStoreGraphResult(SparqlParameterizedString queryString)
        {
            var sparqlParser = new SparqlQueryParser();

            AddAllColidNamespaces(queryString);

            var query = sparqlParser.ParseFromString(queryString);

            Object results = _processor.ProcessQuery(query);

            if (results is IGraph)
            {
                //Print out the Results
                IGraph rset = (VDS.RDF.Graph)results;
                rset.BaseUri = new Uri("https://pid.bayer.com/fake-base-uri");
                return(rset);
            }

            return(null);
        }
        public void SparqlGroupByRefactor7()
        {
            String query = "SELECT ?s WHERE { ?s ?p ?o } GROUP BY (?s)";

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

            String queryStr = q.ToString();

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

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

            Console.WriteLine("Formatted String");
            Console.WriteLine(queryStrFmt);
            Assert.Contains("GROUP BY ?s", queryStrFmt);
        }
        public void SparqlServiceUsingDBPediaAndBindings()
        {
            Skip.IfNot(TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing), "Test Config marks Remote Parsing as unavailable, test cannot be run");

            String            query  = "SELECT * WHERE { SERVICE <http://dbpedia.org/sparql> { ?s a ?type } } VALUES ?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.True(false, "Should have returned a SPARQL Result Set");
            }
        }
Esempio n. 9
0
        public List <TriplesDM> GetTriples(string query)
        {
            List <TriplesDM>  triples = new List <TriplesDM>();
            SparqlQueryParser parser  = new SparqlQueryParser();
            SparqlQuery       q       = parser.ParseFromString(query);

            foreach (var item in q.RootGraphPattern.TriplePatterns)
            {
                triples.Add(new TriplesDM()
                {
                    Subject   = (item as TriplePattern).Subject.ToString(),
                    Predicate = (item as TriplePattern).Predicate.ToString(),
                    Obj       = (item as TriplePattern).Object.ToString()
                });
                var subject   = (item as TriplePattern).Subject;
                var predicate = (item as TriplePattern).Predicate;
                var obj       = (item as TriplePattern).Object;
            }
            return(triples);
        }
Esempio n. 10
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;
                }
            }
        }
Esempio n. 11
0
        public void SparqlFormattingFilter2()
        {
            String            query  = "SELECT * WHERE { { ?s ?p ?o } FILTER(REGEX(?o, 'search', 'i')) }";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);

            Console.WriteLine("ToString() form:");
            String toString = q.ToString();

            Console.WriteLine(toString);
            Console.WriteLine();
            Console.WriteLine("Format() form:");
            String formatted = this._formatter.Format(q);

            Console.WriteLine(formatted);

            Assert.IsTrue(toString.Contains("FILTER"), "ToString() form should contain FILTER");
            Assert.IsTrue(toString.Contains("i"), "ToString() form should contain i option");
            Assert.IsTrue(formatted.Contains("FILTER"), "Format() form should contain FILTER");
            Assert.IsTrue(toString.Contains("i"), "Format() form should contain i option");
        }
Esempio n. 12
0
        public static String GetAmrNode(IGraph g, AMREduSentence sentence)
        {
            String            result  = string.Empty;
            SparqlQueryParser qparser = new SparqlQueryParser();
            var         str           = "SELECT ?p WHERE { <" + sentence.urlid + ">  <http://amr.isi.edu/rdf/core-amr#root> ?p }";
            SparqlQuery q             = qparser.ParseFromString(str);
            var         rset          = (SparqlResultSet)g.ExecuteQuery(q);
            var         SB            = new StringBuilder();

            if (rset.Result && rset.Results.Count > 0)
            {
                foreach (var set in rset.Results)
                {
                    foreach (var r in set)
                    {
                        result = r.Value.ToString();
                    }
                }
            }
            return(result);
        }
Esempio n. 13
0
 public void InsertValuesClause()
 {
     var g = new Graph();
     g.LoadFromFile("resources\\rvesse.ttl");
     var parser = new SparqlQueryParser();
     SparqlQuery startingQuery =
         parser.ParseFromString("SELECT * WHERE { <http://www.dotnetrdf.org/people#rvesse> ?p ?o }");
     var bindingVars = new List<string> {"p"};
     var binding = new BindingsPattern(bindingVars);
     binding.AddTuple(new BindingTuple(bindingVars, new List<PatternItem>
     {
         new NodeMatchPattern(g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/name")))
     }));
     binding.AddTuple(new BindingTuple(bindingVars, new List<PatternItem>
     {
         new NodeMatchPattern(g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/givenname")))
     }));
     startingQuery.RootGraphPattern.AddInlineData(binding);
     
     g.ExecuteQuery(startingQuery).Should().BeAssignableTo<SparqlResultSet>().Which.Count.Should().Be(2);
 }
        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));
                    }
                }
            }
        }
Esempio n. 15
0
        public SparqlResultSet RunQueryDataTable(String queryString)
        {
            queryString =
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n " +
                "PREFIX owl: <http://www.w3.org/2002/07/owl#> \n " +
                "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n " +
                "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> \n " + queryString;

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

            Object resultsSet = Ontology.ExecuteQuery(query);

            if (resultsSet is SparqlResultSet)
            {
                return((SparqlResultSet)resultsSet);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 16
0
        public void SparqlBindToExistingVariableLazy()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT * WHERE { ?s ?p ?o . BIND(?s AS ?p) } LIMIT 1";

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

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

            SparqlQueryParser parser = new SparqlQueryParser();

            try
            {
                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();

                store.ExecuteQuery(q);
                Assert.Fail("Expected a RdfParseException/RdfQueryException to be thrown");
            }
            catch (RdfParseException parseEx)
            {
                Console.WriteLine("Parsing Error thrown as expected");
                TestTools.ReportError("Parser Error", parseEx);
            }
            catch (RdfQueryException queryEx)
            {
                Console.WriteLine("Query Error thrown as expected");
                TestTools.ReportError("Query Error", queryEx);
            }
            catch (Exception ex)
            {
                TestTools.ReportError("Unexpected Error", ex);
                Assert.Fail("Did not get a RdfParseException/RdfQueryException as expected");
            }
        }
        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);
        }
Esempio n. 18
0
        private void ProcessPartialResult(
            SparqlParameterizedString parametrizedCommandText,
            SparqlQueryVariables queryVariables,
            SparqlQueryParser parser,
            List <SparqlResult> result,
            SparqlResult row,
            ParallelLoopState state)
        {
            if (state.IsStopped)
            {
                return;
            }

            SparqlQuery query;

            lock (parametrizedCommandText)
            {
                parametrizedCommandText.SetUri("graph", ((IUriNode)row[queryVariables.MetaGraph]).Uri);
                query = parser.ParseFromString(parametrizedCommandText);
            }

            query.Timeout = Timeout;
            try
            {
                var graphResult = ((SparqlResultSet)_processor.ProcessQuery(query)).Results;
                lock (result)
                {
                    result.AddRange(graphResult);
                }
            }
            catch (RdfQueryTimeoutException)
            {
                state.Stop();
                lock (result)
                {
                    result.Clear();
                }
            }
        }
Esempio n. 19
0
        public override org.openrdf.query.Query prepareQuery(org.openrdf.query.QueryLanguage ql, string str)
        {
            if (!this.SupportsQueryLanguage(ql))
            {
                throw UnsupportedQueryLanguage(ql);
            }
            try
            {
                SparqlQueryParser parser = new SparqlQueryParser();
                SparqlQuery       q      = parser.ParseFromString(str);

                switch (q.QueryType)
                {
                case SparqlQueryType.Ask:
                    return(new InMemoryBooleanQuery(str, this._store));

                case SparqlQueryType.Construct:
                case SparqlQueryType.Describe:
                case SparqlQueryType.DescribeAll:
                    return(new InMemoryGraphQuery(str, this._store));

                case SparqlQueryType.Select:
                case SparqlQueryType.SelectAll:
                case SparqlQueryType.SelectAllDistinct:
                case SparqlQueryType.SelectAllReduced:
                case SparqlQueryType.SelectDistinct:
                case SparqlQueryType.SelectReduced:
                    return(new InMemoryTupleQuery(str, this._store));

                case SparqlQueryType.Unknown:
                default:
                    throw new dotSesameQuery.MalformedQueryException("Unable to parse the given Query into a valid SPARQL Query as the Query Type is unknown");
                }
            }
            catch (RdfParseException parseEx)
            {
                throw new dotSesameQuery.MalformedQueryException("Unable to parse the given Query into a valid SPARQL Query due to the following error: " + parseEx.Message);
            }
        }
Esempio n. 20
0
        public void LoadRoot(IGraph graph)
        {
            SparqlQueryParser qparser  = new SparqlQueryParser();
            StringBuilder     querystr = new StringBuilder();

            querystr.AppendLine("PREFIX amr-core: <http://amr.isi.edu/rdf/core-amr#>");
            querystr.AppendLine("PREFIX amr-data: <http://amr.isi.edu/amr_data#>");
            querystr.AppendLine("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
            querystr.AppendLine("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>");
            querystr.AppendLine("PREFIX amr-terms: <http://amr.isi.edu/rdf/amr-terms#>");
            querystr.Append("SELECT ?root ");
            querystr.Append("WHERE {");
            querystr.Append("@sentenceuri amr-core:root ?root ");
            querystr.Append("}");

            SparqlParameterizedString command = new SparqlParameterizedString();

            command.CommandText = querystr.ToString();
            command.SetUri("sentenceuri", this.urlid);

            SparqlQuery q = qparser.ParseFromString(command);

            var rset = (SparqlResultSet)graph.ExecuteQuery(q);
            var SB   = new StringBuilder();

            if (rset.Result && rset.Results.Count > 0)
            {
                foreach (var result in rset.Results)
                {
                    this.Root    = new AMRNode();
                    this.Root.Id = ((UriNode)result.ElementAt(0).Value).Uri;
                    LoadData(graph, this.Root);
                    LoadChildren(graph, this.Root, new List <AMRNode>()
                    {
                        this.Root
                    });
                }
            }
        }
Esempio n. 21
0
        public void SparqlBindScope6()
        {
            String query = @"PREFIX : <http://example.org>
SELECT *
WHERE
{
  {
    GRAPH ?g { :s :p ?o }
    BIND (?g AS ?in)
  }
  UNION
  {
    :s :p ?o .
    BIND('default' AS ?in)
  }
}";

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

            Console.WriteLine(q.ToString());

            ISparqlAlgebra algebra = q.ToAlgebra();

            Console.WriteLine(algebra.ToString());
            Assert.IsInstanceOfType(algebra, typeof(Select));

            algebra = ((IUnaryOperator)algebra).InnerAlgebra;
            Assert.IsInstanceOfType(algebra, typeof(Union));

            IUnion         union = (Union)algebra;
            ISparqlAlgebra lhs   = union.Lhs;

            Assert.IsInstanceOfType(lhs, typeof(Extend));

            ISparqlAlgebra rhs = union.Rhs;

            Assert.IsInstanceOfType(rhs, typeof(Join));
        }
Esempio n. 22
0
        public void SparqlEvaluationGraphNonExistentUri()
        {
            String      query     = "SELECT * WHERE { GRAPH <http://example.org/noSuchGraph> { ?s ?p ?o } }";
            TripleStore store     = new TripleStore();
            var         processor = new LeviathanQueryProcessor(store);
            var         parser    = new SparqlQueryParser();
            var         q         = parser.ParseFromString(query);
            Object      results   = processor.ProcessQuery(q);

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

                SparqlResultSet rset = (SparqlResultSet)results;
                Assert.True(rset.IsEmpty, "Result Set should be empty");
                Assert.Equal(3, rset.Variables.Count());
            }
            else
            {
                Assert.True(false, "Query should have returned a SPARQL Result Set");
            }
        }
Esempio n. 23
0
        public void SparqlResultSetToDataTable6()
        {
            String            query  = "ASK WHERE {?s <http://example.org/noSuchPredicate> ?o}";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);

            Graph g = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");

            Object results = g.ExecuteQuery(q);

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

                DataTable table = (DataTable)rset;

                Assert.IsTrue(rset.ResultsType == SparqlResultsType.Boolean);
                Assert.AreEqual(table.Columns.Count, 1, "Should only be one Column");
                Assert.AreEqual(table.Rows.Count, 1, "Should only be one Row");
                Assert.IsFalse((bool)table.Rows[0]["ASK"], "Should be false");

                foreach (DataRow row in table.Rows)
                {
                    foreach (DataColumn col in table.Columns)
                    {
                        Object temp = row[col];
                        Console.Write(col.ColumnName + " = " + ((temp != null) ? temp.ToString() : String.Empty) + " , ");
                    }
                    Console.WriteLine();
                }
            }
            else
            {
                Assert.Fail("Query should have returned a Result Set");
            }
        }
        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 void SparqlResultSetToDataTable5()
        {
            String            query  = "ASK WHERE {?s ?p ?o}";
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);

            Graph g = new Graph();

            FileLoader.Load(g, "resources\\InferenceTest.ttl");

            Object results = g.ExecuteQuery(q);

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

                DataTable table = rset.ToDataTable();

                Assert.True(rset.ResultsType == SparqlResultsType.Boolean);
                Assert.Equal(table.Columns.Count, 1);
                Assert.Equal(table.Rows.Count, 1);
                Assert.True((bool)table.Rows[0]["ASK"], "Should be true");

                foreach (DataRow row in table.Rows)
                {
                    foreach (DataColumn col in table.Columns)
                    {
                        Object temp = row[col];
                        Console.Write(col.ColumnName + " = " + ((temp != null) ? temp.ToString() : String.Empty) + " , ");
                    }
                    Console.WriteLine();
                }
            }
            else
            {
                Assert.True(false, "Query should have returned a Result Set");
            }
        }
Esempio n. 26
0
        public void SparqlServiceUsingDBPedia()
        {
            if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing))
            {
                throw new SkipTestException("Test Config marks Remote Parsing as unavailable, test cannot be run");
            }

            String            query  = "SELECT * WHERE { SERVICE <http://dbpedia.org/sparql> { ?s a ?type } } LIMIT 10";
            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.True(false, "Should have returned a SPARQL Result Set");
            }
        }
        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));
        }
Esempio n. 29
0
        public void SparqlBindScope5()
        {
            String query = @"PREFIX : <http://example.org>
SELECT *
WHERE
{
  GRAPH ?g { :s :p ?o }
  BIND (?g AS ?in)
}";

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

            Console.WriteLine(q.ToString());

            ISparqlAlgebra algebra = q.ToAlgebra();

            Console.WriteLine(algebra.ToString());
            Assert.IsInstanceOfType(algebra, typeof(Select));

            algebra = ((IUnaryOperator)algebra).InnerAlgebra;
            Assert.IsInstanceOfType(algebra, typeof(Extend));
        }
Esempio n. 30
0
        /// <summary>
        /// Processes a SPARQL Query against the Knowledge Base passing the results to the RDF or Results handler as appropriate
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="callback">Callback to invoke once handling of results has completed</param>
        /// <param name="state">State to pass to the callback</param>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery, QueryCallback callback, Object state)
        {
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(sparqlQuery);

            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri));

            switch (q.QueryType)
            {
            case SparqlQueryType.Ask:
            case SparqlQueryType.Select:
            case SparqlQueryType.SelectAll:
            case SparqlQueryType.SelectAllDistinct:
            case SparqlQueryType.SelectAllReduced:
            case SparqlQueryType.SelectDistinct:
            case SparqlQueryType.SelectReduced:
                endpoint.QueryWithResultSet(sparqlQuery, (rs, _) =>
                {
                    resultsHandler.Apply(rs);
                    callback(rdfHandler, resultsHandler, state);
                }, state);
                break;

            case SparqlQueryType.Construct:
            case SparqlQueryType.Describe:
            case SparqlQueryType.DescribeAll:
                endpoint.QueryWithResultGraph(sparqlQuery, (g, _) =>
                {
                    rdfHandler.Apply(g);
                    callback(rdfHandler, resultsHandler, state);
                }, state);
                break;

            default:
                throw new RdfQueryException("Cannot execute unknown query types against Pellet Server");
            }
        }