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); }
/// <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 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"); } }
public void SparqlServiceWithNonExistentService() { String query = "SELECT * WHERE { SERVICE <http://www.dotnetrdf.org/noSuchService> { ?s a ?type } } LIMIT 10"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(new TripleStore()); try { Object results = processor.ProcessQuery(q); Assert.Fail("Should have errored"); } catch (RdfQueryException queryEx) { Console.WriteLine("Errored as expected"); TestTools.ReportError("Query Error", queryEx, false); } }
public IEnumerable<IDataObject> BindRdfDataObjects(IGraph g, IList<OrderingDirection> orderingDirections) { var p = new LeviathanQueryProcessor(new InMemoryDataset(g)); var queryString = MakeOrderedResourceQuery(orderingDirections); var sparqlParser = new SparqlQueryParser(); var query = sparqlParser.ParseFromString(queryString); var queryResultSet = p.ProcessQuery(query) as SparqlResultSet; if (queryResultSet != null) { foreach (var row in queryResultSet.Results) { INode uriNode; if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode) { yield return BindRdfDataObject((IUriNode) uriNode, g); } } } }
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"); }
public static void ApplyInference(IGraph graph, IGraph schema) { string inverseOf = @" PREFIX owl: <http://www.w3.org/2002/07/owl#> CONSTRUCT { ?y ?q ?x } WHERE { ?p owl:inverseOf ?q . ?x ?p ?y . } "; var parser = new SparqlQueryParser(); var rules = new List<SparqlQuery>(); rules.Add(parser.ParseFromString(inverseOf)); var store = new TripleStore(); store.Add(graph, true); store.Add(schema, true); var queryProcessor = new LeviathanQueryProcessor(store); while (true) { int before = store.Triples.Count(); foreach (var rule in rules) { IGraph inferred = (IGraph)queryProcessor.ProcessQuery(rule); //store.Add(inferred); graph.Merge(inferred); } int after = store.Triples.Count(); if (after == before) { break; } } }
public void 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); } }
public LoadedGraph(LeviathanQueryProcessor queryProcessor, IGraph graph, InMemoryDataset dataset) { QueryProcessor = queryProcessor; Graph = graph; Dataset = dataset; }
/// <summary> /// Makes a SPARQL Query against the Store /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <returns></returns> public Object Query(String sparqlQuery) { if (this._queryParser == null) this._queryParser = new SparqlQueryParser(); SparqlQuery q = this._queryParser.ParseFromString(sparqlQuery); if (this._queryProcessor == null) this._queryProcessor = new LeviathanQueryProcessor(this._dataset); return this._queryProcessor.ProcessQuery(q); }
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)); }
public static void AddData(IDocumentStore store, string pGLoc) { //find all the zip files var zipFiles = Directory.GetFiles(pGLoc, "*.zip", SearchOption.AllDirectories); Stream unzippedEntryStream; foreach (var zipPath in zipFiles) { try { using (ZipArchive archive = System.IO.Compression.ZipFile.Open(zipPath, ZipArchiveMode.Read)) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) { try { FileInfo file = new FileInfo(entry.FullName); unzippedEntryStream = entry.Open(); // .Open will return a stream // Process entry data here Stream newStream = new MemoryStream(); unzippedEntryStream.CopyTo(newStream); StreamReader reader = new StreamReader(newStream, System.Text.Encoding.UTF8, true); reader.BaseStream.Position = 0; string text = reader.ReadToEnd(); reader.Close(); reader.Dispose(); IGraph g = new Graph(); IGraph h = new Graph(); string parsedBookId = Path.GetFileNameWithoutExtension(entry.Name).Contains("-") ? Path.GetFileNameWithoutExtension(entry.Name).Substring(0, Path.GetFileNameWithoutExtension(entry.Name).IndexOf("-")) : Path.GetFileNameWithoutExtension(entry.Name); if (Int32.TryParse(parsedBookId, out int bookId)) { //Load using Filename FileLoader.Load(h, pGLoc + $"\\rdf-files\\cache\\epub\\{parsedBookId}\\pg{parsedBookId}.rdf"); TripleStore tstore = 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(tstore, new Uri("http://purl.org/dc/terms")); //Get the Query processor ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds); NTriplesFormatter formatter = new NTriplesFormatter(); foreach (Triple t in h.Triples) { System.Console.WriteLine(t.ToString(formatter)); } var nodes = h.GetTriplesWithPredicate(new Uri("http://purl.org/dc/terms/title")).First().Nodes.ToList(); var title = h.GetTriplesWithPredicate(new Uri("http://purl.org/dc/terms/title")).First().Nodes.ToList()[2].ToString(); var titlestring = h.GetTriplesWithPredicate(new Uri("http://purl.org/dc/terms/title")).First().Nodes.FirstOrDefault(); //var creatornodes = h.GetTriplesWithPredicate(new Uri("http://purl.org/dc/terms/creator")).First().Nodes.ToList(); var creatorName = h.GetTriplesWithPredicate(new Uri("http://www.gutenberg.org/2009/pgterms/name")).First().Nodes.ToList()[2].ToString(); var languagenodes = h.GetTriplesWithPredicate(new Uri("http://purl.org/dc/terms/language")).First().Nodes; //var language = languagenodes.ToList()[2].Graph.GetTriplesWithPredicate(new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")).First().Nodes.ToList()[2].ToString(); GutBook book = new GutBook() { Author = creatorName, BookId = bookId, Text = text, Title = title, Language = "en" }; var Session = store.OpenSession(); var existingBook = from d in Session.Query <GutBook>() where d.BookId.Equals(bookId) select d; List <GutBook> gutBooks = Session .Query <GutBook>() .Where(x => x.BookId == bookId) .ToList(); if (gutBooks == null || gutBooks.Count().Equals(0)) { using (BulkInsertOperation bulkInsert = store.BulkInsert()) { book.Version = 1.0; bulkInsert.Store(book); } } else { // do a patch string id = Session.Advanced.GetDocumentId(gutBooks.First()); GutBook oldBook = Session.Load <GutBook>(id); if (string.IsNullOrEmpty(oldBook.Text)) { oldBook.Text = text; oldBook.Version = oldBook.Version + 0.1; AttachmentName[] attachmentNames = Session.Advanced.Attachments.GetNames(oldBook); foreach (AttachmentName attachmentName in attachmentNames) { string name = attachmentName.Name; string contentType = attachmentName.ContentType; string hash = attachmentName.Hash; long size = attachmentName.Size; } Stream attachStream = new MemoryStream(); unzippedEntryStream.CopyTo(attachStream); Session.Advanced.Attachments.Store(id, $"{oldBook.BookId}.txt", attachStream, "text/plain"); } } Session.SaveChanges(); } } catch (RdfParseException parseEx) { //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc. System.Console.WriteLine("Parser Error"); System.Console.WriteLine(parseEx.Message); } catch (RdfException rdfEx) { //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace System.Console.WriteLine("RDF Error"); System.Console.WriteLine(rdfEx.Message); } catch (Exception ex) { System.Console.WriteLine("Unexpected Error"); System.Console.WriteLine(ex.Message); } } } } } catch (Exception ex) { System.Console.WriteLine("Unexpected Error"); System.Console.WriteLine(ex.Message); } } var something = ""; }
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"); } }
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()); }
public void Evaluate(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, ISparqlDataset dataset) { LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); processor.ProcessQuery(rdfHandler, resultsHandler, this); }
/// <summary> /// Executes a SPARQL Query on the Triple Store /// </summary> /// <param name="query">SPARQL Query as a <see cref="SparqlQuery">SparqlQuery</see> instance</param> /// <returns></returns> public virtual Object ExecuteQuery(SparqlQuery query) { if (this._processor == null) this._processor = new LeviathanQueryProcessor(new InMemoryQuadDataset(this)); return this._processor.ProcessQuery(query); }
public Object Evaluate(ISparqlDataset dataset) { LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); return processor.ProcessQuery(this); }
public FakeTripleStoreRepository(Dictionary <string, string> graphs) { _store = CreateNewTripleStore(graphs); _dataset = new InMemoryDataset(_store); _processor = new LeviathanQueryProcessor(_dataset); }
/// <summary>Initializes a new instance of the <see cref="InMemoryTripleStoreSparqlCommandExecutionStrategy" /> class.</summary> /// <param name="store">Target in-memory triple store.</param> /// <param name="metaGraphUri">Meta-graph uri.</param> public InMemoryTripleStoreSparqlCommandExecutionStrategy(IInMemoryQueryableStore store, Uri metaGraphUri) : base(store, metaGraphUri) { _processor = new LeviathanQueryProcessor(new InMemoryQuadDataset((IInMemoryQueryableStore)Store, MetaGraphUri)); }
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; }
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); } } }
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); } }
/// <summary> /// Executes a SPARQL Query on the Triple Store processing the results with an appropriate handler from those provided /// </summary> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="query">SPARQL Query as unparsed String</param> public virtual void ExecuteQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query) { if (this._processor == null) this._processor = new LeviathanQueryProcessor(new InMemoryQuadDataset(this)); this._processor.ProcessQuery(rdfHandler, resultsHandler, query); }
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; } }
/// <summary> /// Tries to load a SPARQL Query Processor based on information from the Configuration Graph /// </summary> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> /// <param name="targetType">Target Type</param> /// <param name="obj">Output Object</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; ISparqlQueryProcessor processor = null; INode storeObj; Object temp; switch (targetType.FullName) { case LeviathanQueryProcessor: INode datasetObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingDataset)); if (datasetObj != null) { temp = ConfigurationLoader.LoadObject(g, datasetObj); if (temp is ISparqlDataset) { processor = new LeviathanQueryProcessor((ISparqlDataset)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingDataset property points to an Object that cannot be loaded as an object which implements the ISparqlDataset interface"); } } else { //If no dnr:usingDataset try dnr:usingStore instead storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingStore)); if (storeObj == null) return false; temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is IInMemoryQueryableStore) { processor = new LeviathanQueryProcessor((IInMemoryQueryableStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the IInMemoryQueryableStore interface"); } } break; case SimpleQueryProcessor: storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingStore)); if (storeObj == null) return false; temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is INativelyQueryableStore) { processor = new SimpleQueryProcessor((INativelyQueryableStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Simple Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the INativelyQueryableStore interface"); } break; #if !NO_STORAGE case GenericQueryProcessor: INode managerObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyGenericManager)); if (managerObj == null) return false; temp = ConfigurationLoader.LoadObject(g, managerObj); if (temp is IQueryableGenericIOManager) { processor = new GenericQueryProcessor((IQueryableGenericIOManager)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Generic Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object that cannot be loaded as an object which implements the IQueryableGenericIOManager interface"); } break; #endif #if !SILVERLIGHT case RemoteQueryProcessor: INode endpointObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyEndpoint)); if (endpointObj == null) return false; temp = ConfigurationLoader.LoadObject(g, endpointObj); if (temp is SparqlRemoteEndpoint) { processor = new RemoteQueryProcessor((SparqlRemoteEndpoint)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Remote Query Processor identified by the Node '" + objNode.ToSafeString() + "' as the value given for the dnr:endpoint property points to an Object that cannot be loaded as an object which is a SparqlRemoteEndpoint"); } break; case PelletQueryProcessor: String server = ConfigurationLoader.GetConfigurationValue(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyServer)); if (server == null) return false; String kb = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyStore)); if (kb == null) return false; processor = new PelletQueryProcessor(new Uri(server), kb); break; #endif } obj = processor; return (processor != null); }
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"); } }
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; }
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); }
private void SparqlQueryThreadSafeEvaluationActual() { String query1 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/1> { ?s ?p ?o } }"; String query2 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/2> { ?s ?p ?o } }"; SparqlQuery q1 = this._parser.ParseFromString(query1); SparqlQuery q2 = this._parser.ParseFromString(query2); Assert.IsFalse(q1.UsesDefaultDataset, "Query 1 should not be thread safe"); Assert.IsFalse(q2.UsesDefaultDataset, "Query 2 should not be thread safe"); InMemoryDataset dataset = new InMemoryDataset(); Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); g.BaseUri = new Uri("http://example.org/1"); Graph h = new Graph(); h.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.Functions.LeviathanFunctionLibrary.ttl"); h.BaseUri = new Uri("http://example.org/2"); dataset.AddGraph(g); dataset.AddGraph(h); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); QueryWithGraphDelegate d = new QueryWithGraphDelegate(this.QueryWithGraph); IAsyncResult r1 = d.BeginInvoke(q1, processor, null, null); IAsyncResult r2 = d.BeginInvoke(q2, processor, null, null); WaitHandle.WaitAll(new WaitHandle[] { r1.AsyncWaitHandle, r2.AsyncWaitHandle }); IGraph gQuery = d.EndInvoke(r1); Assert.AreEqual(g, gQuery, "Query 1 Result not as expected"); IGraph hQuery = d.EndInvoke(r2); Assert.AreEqual(h, hQuery, "Query 2 Result not as expected"); Assert.AreNotEqual(g, h, "Graphs should not be different"); }
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 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 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; }
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"); }
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; }
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; } }
private void SparqlQueryAndUpdateThreadSafeEvaluationActual() { String query1 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/1> { ?s ?p ?o } }"; String query2 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/2> { ?s ?p ?o } }"; String query3 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/3> { ?s ?p ?o } }"; String update1 = "INSERT DATA { GRAPH <http://example.org/3> { <ex:subj> <ex:pred> <ex:obj> } }"; SparqlQuery q1 = this._parser.ParseFromString(query1); SparqlQuery q2 = this._parser.ParseFromString(query2); SparqlQuery q3 = this._parser.ParseFromString(query3); Assert.IsFalse(q1.UsesDefaultDataset, "Query 1 should not be thread safe"); Assert.IsFalse(q2.UsesDefaultDataset, "Query 2 should not be thread safe"); Assert.IsFalse(q3.UsesDefaultDataset, "Query 3 should not be thread safe"); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(update1); InMemoryDataset dataset = new InMemoryDataset(); Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); g.BaseUri = new Uri("http://example.org/1"); Graph h = new Graph(); h.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.Functions.LeviathanFunctionLibrary.ttl"); h.BaseUri = new Uri("http://example.org/2"); Graph i = new Graph(); i.BaseUri = new Uri("http://example.org/3"); dataset.AddGraph(g); dataset.AddGraph(h); dataset.AddGraph(i); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(dataset); LeviathanUpdateProcessor upProcessor = new LeviathanUpdateProcessor(dataset); QueryWithGraphDelegate d = new QueryWithGraphDelegate(this.QueryWithGraph); RunUpdateDelegate d2 = new RunUpdateDelegate(this.RunUpdate); IAsyncResult r1 = d.BeginInvoke(q1, processor, null, null); IAsyncResult r2 = d.BeginInvoke(q2, processor, null, null); IAsyncResult r3 = d.BeginInvoke(q3, processor, null, null); IAsyncResult r4 = d2.BeginInvoke(cmds, upProcessor, null, null); WaitHandle.WaitAll(new WaitHandle[] { r1.AsyncWaitHandle, r2.AsyncWaitHandle, r3.AsyncWaitHandle, r4.AsyncWaitHandle }); IGraph gQuery = d.EndInvoke(r1); Assert.AreEqual(g, gQuery, "Query 1 Result not as expected"); IGraph hQuery = d.EndInvoke(r2); Assert.AreEqual(h, hQuery, "Query 2 Result not as expected"); IGraph iQuery = d.EndInvoke(r3); if (iQuery.IsEmpty) { Console.WriteLine("Query 3 executed before the INSERT DATA command - running again to get the resulting graph"); iQuery = this.QueryWithGraph(q3, processor); } else { Console.WriteLine("Query 3 executed after the INSERT DATA command"); } //Test iQuery against an empty Graph Assert.IsFalse(iQuery.IsEmpty, "Graph should not be empty as INSERT DATA should have inserted a Triple"); Assert.AreNotEqual(new Graph(), iQuery, "Graphs should not be equal"); Assert.AreNotEqual(g, h, "Graphs should not be different"); }
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()); } }
/// <summary> /// Tries to load a SPARQL Query Processor based on information from the Configuration Graph /// </summary> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> /// <param name="targetType">Target Type</param> /// <param name="obj">Output Object</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; ISparqlQueryProcessor processor = null; INode storeObj; Object temp; INode propStorageProvider = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStorageProvider)); switch (targetType.FullName) { case LeviathanQueryProcessor: INode datasetObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingDataset))); if (datasetObj != null) { temp = ConfigurationLoader.LoadObject(g, datasetObj); if (temp is ISparqlDataset) { processor = new LeviathanQueryProcessor((ISparqlDataset)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingDataset property points to an Object that cannot be loaded as an object which implements the ISparqlDataset interface"); } } else { // If no dnr:usingDataset try dnr:usingStore instead storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore))); if (storeObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is IInMemoryQueryableStore) { processor = new LeviathanQueryProcessor((IInMemoryQueryableStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the IInMemoryQueryableStore interface"); } } break; case SimpleQueryProcessor: storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore))); if (storeObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is INativelyQueryableStore) { processor = new SimpleQueryProcessor((INativelyQueryableStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Simple Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the INativelyQueryableStore interface"); } break; case GenericQueryProcessor: INode managerObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propStorageProvider); if (managerObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, managerObj); if (temp is IQueryableStorage) { processor = new GenericQueryProcessor((IQueryableStorage)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Generic Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object that cannot be loaded as an object which implements the IQueryableStorage interface"); } break; case RemoteQueryProcessor: INode endpointObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpoint))); if (endpointObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, endpointObj); if (temp is SparqlRemoteEndpoint) { processor = new RemoteQueryProcessor((SparqlRemoteEndpoint)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Remote Query Processor identified by the Node '" + objNode.ToSafeString() + "' as the value given for the dnr:endpoint property points to an Object that cannot be loaded as an object which is a SparqlRemoteEndpoint"); } break; case PelletQueryProcessor: String server = ConfigurationLoader.GetConfigurationValue(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyServer))); if (server == null) { return(false); } String kb = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStore))); if (kb == null) { return(false); } processor = new PelletQueryProcessor(UriFactory.Create(server), kb); break; } obj = processor; return(processor != null); }
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; } }
/// <summary> /// Makes a SPARQL Query against the Store processing the results with the appropriate processor from those given /// </summary> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="sparqlQuery">SPARQL Query</param> /// <returns></returns> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery) { if (this._queryParser == null) this._queryParser = new SparqlQueryParser(); SparqlQuery q = this._queryParser.ParseFromString(sparqlQuery); if (this._queryProcessor == null) this._queryProcessor = new LeviathanQueryProcessor(this._dataset); this._queryProcessor.ProcessQuery(rdfHandler, resultsHandler, q); }
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); } }