public CoffeeAndTea GetPlacesThatServeBreakfastAndTea() { //Then we can parse a SPARQL string into a query SparqlQuery query = _parser.ParseFromString(@" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX foursquare: <http://www.semanticweb.org/hekurankastrati/ontologies/2019/5/foursquare#> SELECT ?place ?address WHERE { ?place foursquare:hasInfo ?info . ?info foursquare:hasAddress ?address { ?place rdf:type foursquare:BreakFast } UNION { ?place rdf:type foursquare:CoffeAndTea } }"); //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(_foursquareGraph); //Get the Query processor ISparqlQueryProcessor processor = new ExplainQueryProcessor(ds); CoffeeAndTea dto = new CoffeeAndTea { Data = new List <Data>() }; //Use the SparqlQueryParser to give us a SparqlQuery object //Should get a Graph back from a CONSTRUCT query Object results = processor.ProcessQuery(query); if (results is SparqlResultSet resultSet) { foreach (SparqlResult result in resultSet.Results) { string addressData = result.TryGetValue("address", out var node) ? ((IUriNode)node).Uri.Fragment.Replace('#', ' ') : string.Empty; string placeData = result.TryGetValue("place", out var placeNode) ? ((IUriNode)placeNode).Uri.Fragment.Replace('#', ' ') : string.Empty; dto.Data.Add(new Data { Address = addressData, Place = placeData }); } // dto.Data.Add(new Data // { // Address = "test", // Place = "asda" // }); } return(dto); }
public TopPosts GetTopVotedPosts(int numberOfResults = 10) { //Then we can parse a SPARQL string into a query SparqlQuery query = _parser.ParseFromString(@" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX reddit: <http://www.semanticweb.org/hekurankastrati/ontologies/2019/4/reddit#> SELECT ?post ?title ?date ?votes WHERE { ?post rdf:type ?type. ?type rdfs:subClassOf* reddit:Post. ?post reddit:hasTitle ?title . ?post reddit:hasDateCreated ?date . ?post reddit:hasVotes ?votes . } ORDER BY DESC(?votes) LIMIT " + numberOfResults); InMemoryDataset ds = new InMemoryDataset(_redditGraph); //Get the Query processor ISparqlQueryProcessor processor = new ExplainQueryProcessor(ds); TopPosts dto = new TopPosts { Data = new List <TopPostsData>() }; Object results = processor.ProcessQuery(query); if (results is SparqlResultSet resultSet) { foreach (SparqlResult result in resultSet.Results) { string post = result.TryGetValue("post", out var node) ? ((IUriNode)node).Uri.Fragment.Replace('#', ' ') : string.Empty; string title = result.TryGetValue("title", out var titleNode) ? ((ILiteralNode)titleNode).Value : string.Empty; string date = result.TryGetValue("date", out var dateNode) ? ((ILiteralNode)dateNode).Value : string.Empty; string votes = result.TryGetValue("votes", out var votesNode) ? ((ILiteralNode)votesNode).Value : string.Empty; dto.Data.Add(new TopPostsData { Post = post, Title = title, Date = date, Votes = votes }); } } return(dto); }
public PlacesAndLikes GetAllLikesForDinnerPlace(string inputPlace) { //Then we can parse a SPARQL string into a query SparqlQuery query = _parser.ParseFromString(@" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX foursquare: <http://www.semanticweb.org/hekurankastrati/ontologies/2019/5/foursquare#> SELECT ?place (COUNT(?profile) as ?likes) WHERE { ?place rdf:type foursquare:" + inputPlace + @" . ?profile rdf:type foursquare:Profile . ?profile foursquare:hasLikedPlace ?place . } GROUP BY ?place"); InMemoryDataset ds = new InMemoryDataset(_foursquareGraph); //Get the Query processor ISparqlQueryProcessor processor = new ExplainQueryProcessor(ds); PlacesAndLikes dto = new PlacesAndLikes { Data = new List <PlacesAndLikesData>() }; Object results = processor.ProcessQuery(query); if (results is SparqlResultSet resultSet) { foreach (SparqlResult result in resultSet.Results) { string place = result.TryGetValue("place", out var node) ? ((IUriNode)node).Uri.Fragment.Replace('#', ' ') : string.Empty; string likes = result.TryGetValue("likes", out var likeNode) ? ((LongNode)likeNode).Value : string.Empty; dto.Data.Add(new PlacesAndLikesData { Place = place, Likes = likes }); } } return(dto); }
public fclsExplanation(SparqlQuery query, long parseTime) { InitializeComponent(); this.lblParseTime.Text = "Took " + parseTime + "ms to parse"; this.txtQuery.Text = this._formatter.Format(query); //First need to create the Explanation using (StreamWriter writer = new StreamWriter("explain.temp", false, Encoding.UTF8)) { ExplainQueryProcessor processor = new ExplainQueryProcessor(new TripleStore()); processor.ExplanationLevel = (ExplanationLevel.OutputToTrace | ExplanationLevel.ShowAll | ExplanationLevel.AnalyseAll | ExplanationLevel.Simulate) ^ ExplanationLevel.ShowThreadID ^ ExplanationLevel.ShowTimings ^ ExplanationLevel.ShowIntermediateResultCount; TextWriterTraceListener listener = new TextWriterTraceListener(writer, "SparqlGUI"); Trace.Listeners.Add(listener); try { Object results = processor.ProcessQuery(query); } catch { throw; } finally { Trace.Listeners.Remove(listener); } writer.Close(); } //Then need to display it using (StreamReader reader = new StreamReader("explain.temp")) { this.txtExplanation.Text = reader.ReadToEnd(); reader.Close(); } }
public fclsExplanation(SparqlQuery query, long parseTime) { InitializeComponent(); this.lblParseTime.Text = "Took " + parseTime + "ms to parse"; this.txtQuery.Text = this._formatter.Format(query); //First need to create the Explanation using (StreamWriter writer = new StreamWriter("explain.temp", false, Encoding.UTF8)) { ExplainQueryProcessor processor = new ExplainQueryProcessor(new TripleStore()); processor.ExplanationLevel = (ExplanationLevel.OutputToTrace | ExplanationLevel.ShowAll | ExplanationLevel.AnalyseAll | ExplanationLevel.Simulate) ^ ExplanationLevel.ShowThreadID ^ ExplanationLevel.ShowTimings ^ ExplanationLevel.ShowIntermediateResultCount; TextWriterTraceListener listener = new TextWriterTraceListener(writer, "SparqlGUI"); Trace.Listeners.Add(listener); try { Object results = processor.ProcessQuery(query); } catch { throw; } finally { Trace.Listeners.Remove(listener); } writer.Close(); } //Then need to display it using (StreamReader reader = new StreamReader("explain.temp")) { this.txtExplanation.Text = reader.ReadToEnd(); reader.Close(); } }
public List <string> GetPlacesWithSocialMedia() { //Then we can parse a SPARQL string into a query SparqlQuery query = _parser.ParseFromString(@" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX foursquare: <http://www.semanticweb.org/hekurankastrati/ontologies/2019/5/foursquare#> SELECT ?socialmedia WHERE { { ?socialmedia rdf:type foursquare:Facebook } UNION { ?socialmedia rdf:type foursquare:Instagram} }"); InMemoryDataset ds = new InMemoryDataset(_foursquareGraph); //Get the Query processor ISparqlQueryProcessor processor = new ExplainQueryProcessor(ds); List <string> places = new List <string>(); Object results = processor.ProcessQuery(query); if (results is SparqlResultSet resultSet) { foreach (SparqlResult result in resultSet.Results) { string place = result.TryGetValue("socialmedia", out var node) ? ((IUriNode)node).Uri.Fragment.Replace('#', ' ') : string.Empty; places.Add(place); } } return(places); }
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) { ExplainQueryProcessor processor = new ExplainQueryProcessor(this._store, this._level); results = processor.ProcessQuery(q); } else { results = this._store.ExecuteQuery(q); } break; case RdfQueryMode.Remote: if (this._explain) Console.Error.WriteLine("rdfQuery: Warning: Cannot explain queries when the query is being sent to a remote endpoint"); this._endpoint.Timeout = Convert.ToInt32(this._timeout); switch (q.QueryType) { case SparqlQueryType.Construct: case SparqlQueryType.Describe: case SparqlQueryType.DescribeAll: results = this._endpoint.QueryWithResultGraph(this._query); break; default: results = this._endpoint.QueryWithResultSet(this._query); break; } break; case RdfQueryMode.Unknown: default: if (this._explain) { ExplainQueryProcessor processor = new ExplainQueryProcessor(new TripleStore(), this._level); processor.ProcessQuery(q); } else { Console.Error.WriteLine("rdfQuery: There were no inputs or a remote endpoint specified in the arguments so no query can be executed"); } return; } } //Select the Output Stream StreamWriter output; if (this._output == null) { output = new StreamWriter(Console.OpenStandardOutput()); } else { output = new StreamWriter(this._output); } if (!this._print) { //Output the Results if (results is SparqlResultSet) { this._resultsWriter.Save((SparqlResultSet)results, output); } else if (results is IGraph) { this._graphWriter.Save((IGraph)results, output); } else { Console.Error.WriteLine("rdfQuery: The Query resulted in an unknown result"); } } else { //If Printing Print the Query then the Algebra SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap); output.WriteLine("Query"); output.WriteLine(formatter.Format(q)); output.WriteLine(); output.WriteLine("Algebra"); output.WriteLine(q.ToAlgebra().ToString()); output.Flush(); output.Close(); } } catch (RdfQueryTimeoutException timeout) { Console.Error.WriteLine("rdfQuery: Query Timeout: " + timeout.Message); if (this._debug) this.DebugErrors(timeout); return; } catch (RdfQueryException queryEx) { Console.Error.WriteLine("rdfQuery: Query Error: " + queryEx.Message); if (this._debug) this.DebugErrors(queryEx); return; } catch (RdfParseException parseEx) { Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message); if (this._debug) this.DebugErrors(parseEx); return; } catch (RdfException rdfEx) { Console.Error.WriteLine("rdfQuery: RDF Error: " + rdfEx.Message); if (this._debug) this.DebugErrors(rdfEx); return; } catch (Exception ex) { Console.Error.WriteLine("rdfQuery: Error: " + ex.Message); if (this._debug) this.DebugErrors(ex); return; } }
private void btnQuery_Click(object sender, EventArgs e) { try { SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery query = parser.ParseFromString(this.txtQuery.Text); query.Timeout = (long)this.numTimeout.Value; query.PartialResultsOnTimeout = this.chkPartialResults.Checked; if (this._tripleCount == 0 && this._noDataWarning) { switch (MessageBox.Show("You have no data loaded to query over - do you wish to run this query anyway? Press Abort if you'd like to load data first, Retry to continue anyway or Ignore to continue anyway and suppress this message during this session", "Continue Query without Data", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Question)) { case DialogResult.Abort: return; case DialogResult.Ignore: //Set the Ignore flag then continue anyway this._noDataWarning = false; break; default: //Continue anyway break; } } this.LogStartQuery(query); //Evaluate the Query Object results; if (this._logExplain) { using (StreamWriter writer = new StreamWriter(this._logfile, true, Encoding.UTF8)) { ExplainQueryProcessor explainer = new ExplainQueryProcessor(this._dataset, (ExplanationLevel.OutputToTrace | ExplanationLevel.ShowAll | ExplanationLevel.AnalyseAll) ^ ExplanationLevel.ShowThreadID); TextWriterTraceListener listener = new TextWriterTraceListener(writer, "SparqlGUI"); Trace.Listeners.Add(listener); try { results = explainer.ProcessQuery(query); } finally { Trace.Listeners.Remove(listener); } writer.Close(); } } else { results = this._processor.ProcessQuery(query); } //Process the Results if (results is IGraph) { this.LogEndQuery(query, (IGraph)results); if (this.chkViewResultsInApp.Checked) { GraphViewerForm graphViewer = new GraphViewerForm((IGraph)results, "SPARQL GUI"); graphViewer.Show(); } else { this._rdfwriter.Save((IGraph)results, "temp" + this._rdfext); System.Diagnostics.Process.Start("temp" + this._rdfext); } } else if (results is SparqlResultSet) { this.LogEndQuery(query, (SparqlResultSet)results); if (this.chkViewResultsInApp.Checked) { ResultSetViewerForm resultSetViewer = new ResultSetViewerForm((SparqlResultSet)results, query.NamespaceMap, "SPARQL GUI"); resultSetViewer.Show(); } else { this._resultswriter.Save((SparqlResultSet)results, "temp" + this._resultsext); System.Diagnostics.Process.Start("temp" + this._resultsext); } } else { throw new RdfException("Unexpected Result Type"); } this.stsLastQuery.Text = "Last Query took " + query.QueryExecutionTime; } catch (RdfParseException parseEx) { this.LogMalformedQuery(parseEx); MessageBox.Show("Query failed to parse:\n" + parseEx.Message, "Query Failed"); } catch (RdfQueryException queryEx) { this.LogFailedQuery(queryEx); MessageBox.Show("Query failed during Execution:\n" + queryEx.Message, "Query Failed"); } catch (Exception ex) { this.LogFailedQuery(ex); MessageBox.Show("Query failed:\n" + ex.Message + "\n" + ex.StackTrace, "Query Failed"); } }
public void RunQuery(String[] args) { //If we can't set options then we abort if (!this.SetOptions(args)) { return; } if (this._query == null) { //Try to read query from Standard In instead this._query = Console.In.ReadToEnd(); if (this._query.Equals(String.Empty)) { Console.Error.WriteLine("rdfQuery: No Query was specified"); return; } } //Parse the Query try { SparqlQuery q = this._parser.ParseFromString(this._query); //Set Timeout if necessary q.Timeout = this._timeout; q.PartialResultsOnTimeout = this._partialResults; //Execute the Query unless print was specified Object results = null; if (!this._print) { switch (this._mode) { case RdfQueryMode.Local: if (this._explain) { var processor = new ExplainQueryProcessor(this._store, this._level); results = processor.ProcessQuery(q); } else { var processor = new LeviathanQueryProcessor(_store); results = processor.ProcessQuery(q); } break; case RdfQueryMode.Remote: if (this._explain) { Console.Error.WriteLine("rdfQuery: Warning: Cannot explain queries when the query is being sent to a remote endpoint"); } this._endpoint.Timeout = Convert.ToInt32(this._timeout); switch (q.QueryType) { case SparqlQueryType.Construct: case SparqlQueryType.Describe: case SparqlQueryType.DescribeAll: results = this._endpoint.QueryWithResultGraph(this._query); break; default: results = this._endpoint.QueryWithResultSet(this._query); break; } break; case RdfQueryMode.Unknown: default: if (this._explain) { ExplainQueryProcessor processor = new ExplainQueryProcessor(new TripleStore(), this._level); processor.ProcessQuery(q); } else { Console.Error.WriteLine("rdfQuery: There were no inputs or a remote endpoint specified in the arguments so no query can be executed"); } return; } } //Select the Output Stream StreamWriter output; if (this._output == null) { output = new StreamWriter(Console.OpenStandardOutput()); } else { output = new StreamWriter(this._output); } if (!this._print) { //Output the Results if (results is SparqlResultSet) { this._resultsWriter.Save((SparqlResultSet)results, output); } else if (results is IGraph) { this._graphWriter.Save((IGraph)results, output); } else { Console.Error.WriteLine("rdfQuery: The Query resulted in an unknown result"); } } else { //If Printing Print the Query then the Algebra SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap); output.WriteLine("Query"); output.WriteLine(formatter.Format(q)); output.WriteLine(); output.WriteLine("Algebra"); output.WriteLine(q.ToAlgebra().ToString()); output.Flush(); output.Close(); } } catch (RdfQueryTimeoutException timeout) { Console.Error.WriteLine("rdfQuery: Query Timeout: " + timeout.Message); if (this._debug) { this.DebugErrors(timeout); } return; } catch (RdfQueryException queryEx) { Console.Error.WriteLine("rdfQuery: Query Error: " + queryEx.Message); if (this._debug) { this.DebugErrors(queryEx); } return; } catch (RdfParseException parseEx) { Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message); if (this._debug) { this.DebugErrors(parseEx); } return; } catch (RdfException rdfEx) { Console.Error.WriteLine("rdfQuery: RDF Error: " + rdfEx.Message); if (this._debug) { this.DebugErrors(rdfEx); } return; } catch (Exception ex) { Console.Error.WriteLine("rdfQuery: Error: " + ex.Message); if (this._debug) { this.DebugErrors(ex); } return; } }
private void btnQuery_Click(object sender, EventArgs e) { try { SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery query = parser.ParseFromString(this.txtQuery.Text); query.Timeout = (long)this.numTimeout.Value; query.PartialResultsOnTimeout = this.chkPartialResults.Checked; if (this._store.Graphs.Count == 0 && this._noDataWarning) { switch (MessageBox.Show("You have no data loaded to query over - do you wish to run this query anyway? Press Abort if you'd like to load data first, Retry to continue anyway or Ignore to continue anyway and suppress this message during this session", "Continue Query without Data", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Question)) { case DialogResult.Abort: return; case DialogResult.Ignore: //Set the Ignore flag then continue anyway this._noDataWarning = false; break; default: //Continue anyway break; } } this.LogStartQuery(query); //Evaluate the Query Object results; if (this._logExplain) { using (StreamWriter writer = new StreamWriter(this._logfile, true, Encoding.UTF8)) { ExplainQueryProcessor explainer = new ExplainQueryProcessor(this._store, (ExplanationLevel.OutputToTrace | ExplanationLevel.ShowAll | ExplanationLevel.AnalyseAll ) ^ ExplanationLevel.ShowThreadID); TextWriterTraceListener listener = new TextWriterTraceListener(writer, "SparqlGUI"); Trace.Listeners.Add(listener); try { results = explainer.ProcessQuery(query); } finally { Trace.Listeners.Remove(listener); } writer.Close(); } } else { results = this._store.ExecuteQuery(query); } //Process the Results if (results is IGraph) { this.LogEndQuery(query, (IGraph)results); if (this.chkViewResultsInApp.Checked) { GraphViewerForm graphViewer = new GraphViewerForm((IGraph)results, "SPARQL GUI"); graphViewer.Show(); } else { this._rdfwriter.Save((IGraph)results, "temp" + this._rdfext); System.Diagnostics.Process.Start("temp" + this._rdfext); } } else if (results is SparqlResultSet) { this.LogEndQuery(query, (SparqlResultSet)results); if (this.chkViewResultsInApp.Checked) { ResultSetViewerForm resultSetViewer = new ResultSetViewerForm((SparqlResultSet)results, "SPARQL GUI"); resultSetViewer.Show(); } else { this._resultswriter.Save((SparqlResultSet)results, "temp" + this._resultsext); System.Diagnostics.Process.Start("temp" + this._resultsext); } } else { throw new RdfException("Unexpected Result Type"); } this.stsLastQuery.Text = "Last Query took " + query.QueryTime + " ms"; } catch (RdfParseException parseEx) { this.LogMalformedQuery(parseEx); MessageBox.Show("Query failed to parse:\n" + parseEx.Message, "Query Failed"); } catch (RdfQueryException queryEx) { this.LogFailedQuery(queryEx); MessageBox.Show("Query failed during Execution:\n" + queryEx.Message, "Query Failed"); } catch (Exception ex) { this.LogFailedQuery(ex); MessageBox.Show("Query failed:\n" + ex.Message + "\n" + ex.StackTrace, "Query Failed"); } }