public static Statement?SelectSingle(this SelectableSource src, SelectFilter filter) { var sink = new FirstStatementSink(); src.Select(filter, sink); return(sink.First); }
public static IList <Statement> SelectList(this SelectableSource src, SelectFilter filter, bool distinct, int maxStatements) { var sink = new StatementListSink(distinct, maxStatements); src.Select(filter, sink); return(sink.List); }
public static Statement?SelectSingle(this SelectableSource src, Statement tpl) { var sink = new FirstStatementSink(); src.Select(tpl, sink); return(sink.First); }
// These methods find minimal self-contained graphs // in a graph by recursively expanding a subgraph. public static MemoryStore FindMSG(SelectableSource store, Entity node) { MemoryStore ret = new MemoryStore(); FindMSG(store, node, ret); return(ret); }
public override bool Filter(Literal resource, SelectableSource targetModel) { string v = resource.Value; int c = v.CompareTo(Pattern); return(CompareFilter(c, Type)); }
public static void FindMSG(SelectableSource store, Entity node, Store msg) { if (node.Uri != null) { throw new ArgumentException("node must be anonymous"); } ResSet nodesSeen = new ResSet(); ResSet nodesToAdd = new ResSet(); nodesToAdd.Add(node); while (nodesToAdd.Count > 0) { ResSet nodes = nodesToAdd; nodesToAdd = new ResSet(); Sink sink = new Sink(msg, nodesToAdd); foreach (Entity n in nodes) { if (nodesSeen.Contains(n)) { continue; } nodesSeen.Add(n); store.Select(new Statement(n, null, null, null), sink); store.Select(new Statement(null, n, null, null), sink); store.Select(new Statement(null, null, n, null), sink); } } }
public override MetaQueryResult MetaQuery(Statement[] graph, SemWeb.Query.QueryOptions options, SelectableSource source) { SemWeb.Query.MetaQueryResult ret = new SemWeb.Query.MetaQueryResult(); ret.QuerySupported = true; ret.NoData = new bool[graph.Length]; for (int i = 0; i < graph.Length; i++) { // Take this statement and replace variables by nulls // to make it a statement template. Statement st = graph[i]; for (int j = 0; j < 4; j++) { if (st.GetComponent(j) is Variable) st.SetComponent(j, null); } // See if the store contains this template. if (st != Statement.All && !source.Contains(st)) { ret.NoData[i] = true; continue; } // Process it further in case we have variables // with known values, in which case if none of the // known values is in the store, we also know this // statement is unanswerable. for (int j = 0; j < 4; j++) { Resource r = graph[i].GetComponent(j); // No need to check the following given the check above. //if (r != null && !(r is Variable) && !source.Contains(r)) // ret.NoData[i] = true; if (r != null && r is Variable && options.VariableKnownValues != null && #if !DOTNET2 options.VariableKnownValues.Contains((Variable)r) #else options.VariableKnownValues.ContainsKey((Variable)r) #endif ) { bool found = false; #if !DOTNET2 foreach (Resource s in (ICollection)options.VariableKnownValues[(Variable)r]) { #else foreach (Resource s in (ICollection<Resource>)options.VariableKnownValues[(Variable)r]) { #endif if (source.Contains(s)) { found = true; break; } } if (!found) { ret.NoData[i] = true; } } } } return ret; }
public void Select(SelectableSource source, QueryResultSink sink) { if (!(query is SelectQuery)) { throw new InvalidOperationException("Only SELECT queries are supported by this method (" + query.GetType() + ")."); } Run(source, sink); }
public virtual void Run(SelectableSource source, TextWriter output) { #if !SILVERLIGHT Run(source, new SparqlXmlQuerySink(output)); #else throw new NotSupportedException(); #endif }
public static bool MatchesFilters(Resource literal, LiteralFilter[] filters, SelectableSource targetModel) { if (literal is Literal) { return(MatchesFilters((Literal)literal, filters, targetModel)); } return(false); }
public override SemWeb.Query.MetaQueryResult MetaQuery(Statement[] graph, SemWeb.Query.QueryOptions options, SelectableSource targetModel) { QueryCheckArg(graph); SemWeb.Query.MetaQueryResult ret = new SemWeb.Query.MetaQueryResult(); ret.QuerySupported = true; // TODO: Best to check also whether variables in the query are even known to us. return ret; }
public static bool DefaultContains(SelectableSource source, Statement template) { StatementExistsSink sink = new StatementExistsSink(); SelectFilter filter = new SelectFilter(template); filter.Limit = 1; source.Select(filter, sink); return(sink.Exists); }
// This method finds all minimal self-contained graphs // by painting nodes colors (the colors happen to be // objects) in one pass over the statements and then doing // a second pass to put each statement mentioning a bnode // into the appropriate graph structure. public static Graph[] FindMSGs(SelectableSource source, bool loadIntoMemory) { FindMSGsSink sink = new FindMSGsSink(source, loadIntoMemory); source.Select(Statement.All, sink); ArrayList graphs = new ArrayList(sink.colors.Keys); return((Graph[])graphs.ToArray(typeof(Graph))); }
public bool Ask(SelectableSource source) { if (!(query is AskQuery)) { throw new InvalidOperationException("Only ASK queries are supported by this method (" + query.GetType() + ")."); } AskQuery q = (AskQuery)query; return(q.execute(new RdfSourceWrapper(source, QueryMeta, this))); }
public static Literal SelectLiteral(this SelectableSource src, Statement tpl) { var st = SelectSingle(src, tpl); if (st.HasValue && st.Value.Object is Literal) { return((Literal)st.Value.Object); } return(null); }
private static bool MatchesFilters(Literal literal, LiteralFilter[] filters, SelectableSource targetModel) { foreach (LiteralFilter filter in filters) { if (!filter.Filter(literal, targetModel)) { return(false); } } return(true); }
public override bool Filter(Literal resource, SelectableSource targetModel) { string v = resource.Value; try { Decimal i = Decimal.Parse(v); int c = i.CompareTo(Number); return(CompareFilter(c, Type)); } catch (Exception e) { return(false); } }
public override void Run(SelectableSource source, TextWriter output) { if (query is AskQuery) Ask(source, output); else if (query is ConstructQuery) Construct(source, output); else if (query is DescribeQuery) Describe(source, output); else if (query is SelectQuery) Select(source, output); else throw new NotSupportedException("Query is of an unsupported type."); }
public override bool Filter(Literal resource, SelectableSource targetModel) { string v = resource.Value; try { TimeSpan i = TimeSpan.Parse(v); int c = i.CompareTo(Value); return(CompareFilter(c, Type)); } catch (Exception) { return(false); } }
public void Describe(SelectableSource source, StatementSink sink) { if (!(query is DescribeQuery)) { throw new InvalidOperationException("Only DESCRIBE queries are supported by this method (" + query.GetType() + ")."); } DescribeQuery q = (DescribeQuery)query; RdfSourceWrapper sourcewrapper = new RdfSourceWrapper(source, QueryMeta, this); RdfGraph graph = q.execute(sourcewrapper); WriteGraph(graph, sourcewrapper, sink); }
public void Construct(SelectableSource source, StatementSink sink) { if (!(query is ConstructQuery)) { throw new InvalidOperationException("Only CONSTRUCT queries are supported by this method (" + query.GetType() + ")."); } ConstructQuery q = (ConstructQuery)query; RdfSourceWrapper sourcewrapper = new RdfSourceWrapper(source, QueryMeta, this); RdfGraph graph = q.execute(sourcewrapper); WriteGraph(graph, sourcewrapper, sink); }
protected virtual void RunQuery(Query query, SelectableSource source, TextWriter output) { if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request["outputMimeType"] != null && System.Web.HttpContext.Current.Request["outputMimeType"] == "text/html") { query.Run(source, new HTMLQuerySink(output)); return; } query.Run(source, output); }
bool MatchesFilters(Resource e, VarOrAnchor var, SelectableSource targetModel) { if (!var.IsVariable) { return(true); } /*foreach (ValueFilter f in variables[var.VarIndex].Filters) { * if (!f.Filter(e, targetModel)) return false; * }*/ return(true); }
protected virtual SelectableSource GetDataSource(out bool closeAfterQuery) { closeAfterQuery = false; if (System.Web.HttpContext.Current == null) { throw new InvalidOperationException("This method is not valid outside of an ASP.NET request."); } string path = System.Web.HttpContext.Current.Request.Path; lock (sources) { SelectableSource source = (SelectableSource)sources[path]; if (source != null) { return(source); } System.Collections.Specialized.NameValueCollection config = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationSettings.GetConfig("sparqlSources"); if (config == null) { throw new InvalidOperationException("No sparqlSources config section is set up."); } string spec = config[path]; if (spec == null) { throw new InvalidOperationException("No data source is set for the path " + path + "."); } bool reuse = true; if (spec.StartsWith("noreuse,")) { reuse = false; closeAfterQuery = true; spec = spec.Substring("noreuse,".Length); } StatementSource src = Store.CreateForInput(spec); if (!(src is SelectableSource)) { src = new MemoryStore(src); } if (reuse) { sources[path] = src; } return((SelectableSource)src); } }
private static void EulerQuery(SelectableSource source, string rules, Statement[] queries) { Store store = new Store(source); Euler engine = new Euler(new N3Reader(new StringReader(rules))); foreach (Proof p in engine.Prove(store, queries)) { foreach (Statement s in p.Proved) { Console.WriteLine(s); } } }
} // not sure... public override void Select(SelectFilter filter, SelectableSource targetModel, StatementSink sink) { if (filter.Subjects == null) { filter.Subjects = new Entity[] { new Variable("subject") } } ; if (filter.Predicates == null) { filter.Predicates = new Entity[] { new Variable("predicate") } } ; if (filter.Objects == null) { filter.Objects = new Entity[] { new Variable("object") } } ; if (filter.Metas == null) { filter.Metas = new Entity[] { Statement.DefaultMeta } } ; foreach (Statement s in filter) // until we can operate on filter directly { ArrayList evidence = prove(rules, targetModel, new Statement[] { s }, -1); if (evidence == null) { continue; // not provable (in max number of steps, if that were given) } foreach (EvidenceItem ei in evidence) { foreach (Statement h in ei.head) // better be just one statement { if (filter.LiteralFilters != null && !LiteralFilter.MatchesFilters(h.Object, filter.LiteralFilters, targetModel)) { continue; } sink.Add(h); } } } }
public Proof[] Prove(SelectableSource world, Statement[] goal) { ArrayList evidence = prove(rules, world, goal, -1); if (evidence == null) { throw new Exception("Could not complete proof within the maximum number of steps allowed."); } ArrayList ret = new ArrayList(); foreach (EvidenceItem ei in evidence) { ret.Add(ei.ToProof()); } return((Proof[])ret.ToArray(typeof(Proof))); }
public void Ask(SelectableSource source, TextWriter output) { bool result = Ask(source); System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter(output); w.Formatting = System.Xml.Formatting.Indented; w.WriteStartElement("sparql"); w.WriteAttributeString("xmlns", "http://www.w3.org/2001/sw/DataAccess/rf1/result"); w.WriteStartElement("head"); w.WriteEndElement(); w.WriteStartElement("results"); w.WriteStartElement("boolean"); w.WriteString(result ? "true" : "false"); w.WriteEndElement(); w.WriteEndElement(); w.WriteEndElement(); w.Close(); }
public static void DefaultSelect(SelectableSource source, SelectFilter filter, StatementSink sink) { // This method should be avoided... if (filter.LiteralFilters != null) { sink = new SemWeb.Filters.FilterSink(filter.LiteralFilters, sink, source); } foreach (Entity subject in filter.Subjects == null ? new Entity[] { null } : filter.Subjects) { foreach (Entity predicate in filter.Predicates == null ? new Entity[] { null } : filter.Predicates) { foreach (Resource objct in filter.Objects == null ? new Resource[] { null } : filter.Objects) { foreach (Entity meta in filter.Metas == null ? new Entity[] { null } : filter.Metas) { source.Select(new Statement(subject, predicate, objct, meta), sink); } } } } }
public override bool Distinct { get { return false; } } // not sure... public override void Select(SelectFilter filter, SelectableSource targetModel, StatementSink sink) { if (filter.Subjects == null) filter.Subjects = new Entity[] { new Variable("subject") }; if (filter.Predicates == null) filter.Predicates = new Entity[] { new Variable("predicate") }; if (filter.Objects == null) filter.Objects = new Entity[] { new Variable("object") }; if (filter.Metas == null) filter.Metas = new Entity[] { Statement.DefaultMeta }; foreach (Statement s in filter) { // until we can operate on filter directly ArrayList evidence = prove(rules, targetModel, new Statement[] { s }, -1); if (evidence == null) continue; // not provable (in max number of steps, if that were given) foreach (EvidenceItem ei in evidence) { foreach (Statement h in ei.head) { // better be just one statement if (filter.LiteralFilters != null && !LiteralFilter.MatchesFilters(h.Object, filter.LiteralFilters, targetModel)) continue; sink.Add(h); } } } }
public override void Run(SelectableSource source, TextWriter output) { if (query is AskQuery) { Ask(source, output); } else if (query is ConstructQuery) { Construct(source, output); } else if (query is DescribeQuery) { Describe(source, output); } else if (query is SelectQuery) { Select(source, output); } else { throw new NotSupportedException("Query is of an unsupported type."); } }
public void Ask(SelectableSource source, TextWriter output) { bool result = Ask(source); if (MimeType == SparqlXmlQuerySink.MimeType || MimeType == "text/xml") { System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter(output); w.Formatting = System.Xml.Formatting.Indented; w.WriteStartElement("sparql"); w.WriteAttributeString("xmlns", "http://www.w3.org/2001/sw/DataAccess/rf1/result"); w.WriteStartElement("head"); w.WriteEndElement(); w.WriteStartElement("boolean"); w.WriteString(result ? "true" : "false"); w.WriteEndElement(); w.WriteEndElement(); w.Flush(); } else if (MimeType == "text/plain") { output.WriteLine(result ? "true" : "false"); } else { } }
public bool Ask(SelectableSource source) { if (!(query is AskQuery)) throw new InvalidOperationException("Only ASK queries are supported by this method (" + query.GetType() + ")."); AskQuery q = (AskQuery)query; return q.execute(new RdfSourceWrapper(source, QueryMeta, this)); }
public abstract void Query(Statement[] graph, QueryOptions options, SelectableSource targetModel, QueryResultSink result);
public abstract void Select(SelectFilter filter, SelectableSource targetModel, StatementSink sink);
public abstract void Run(SelectableSource source, QueryResultSink resultsink);
public static void query (SelectableSource source, Statement filter) { using (RdfWriter writer = new N3Writer (System.Console.Out)) source.Select (filter, writer); }
public override void AddSource(SelectableSource store, string uri) { throw new InvalidOperationException("AddSource is not valid on the MemoryStore."); }
public RdfSourceWrapper(SelectableSource source, Entity meta, Sparql sparql) { this.source = source; QueryMeta = meta; this.sparql = sparql; }
public ResourceView(string resourceUri, SelectableSource source) { Uid = new Entity(resourceUri); Source = source; MaxProperties = 1000; }
public bool Ask(SelectableSource source) { if (!(query is AskQuery)) throw new InvalidOperationException("Only ASK queries are supported by this method (" + query.GetType() + ")."); AskQuery q = (AskQuery)query; RdfSourceWrapper sourcewrapper = BindLogic(source); try { return q.execute(sourcewrapper); } catch (name.levering.ryan.sparql.common.QueryException e) { throw new QueryExecutionException("Error executing query: " + e.Message, e); } }
public StatementIterator(SelectableSource source, SelectFilter filter, RdfSourceWrapper wrapper) { this.source = source; this.filter = filter; this.wrapper = wrapper; this.wantMetas = true; }
public void Select(SelectableSource source, TextWriter output) { Select(source, new SparqlXmlQuerySink(output)); }
public ResourceView(Entity resourceEntity, SelectableSource source) { Uid = resourceEntity; Source = source; MaxProperties = 1000; }
public void Construct(SelectableSource source, TextWriter output) { using (RdfWriter w = RdfWriter.Create(MimeType, output)) Construct(source, w); }
public virtual void ProcessRequest(System.Web.HttpContext context) { try { string query = context.Request["query"]; if (query == null || query.Trim() == "") { throw new QueryFormatException("No query provided."); } if (Debug) { Console.Error.WriteLine(query); Console.Error.WriteLine(); } // Buffer the response so that any errors while // executing don't get outputted after the response // has begun. MemoryStream buffer = new MemoryStream(); bool closeAfterQuery; SelectableSource source = GetDataSource(out closeAfterQuery); try { Query sparql = CreateQuery(query); // Try setting the preferred output MIME type based // on the HTTP Accept header, in the order that we // get them from System.Web (?). if (context.Request.AcceptTypes != null) { foreach (string acceptType in context.Request.AcceptTypes) { // Setting the MIME type may throw, so we // break on the first successful set. try { sparql.MimeType = acceptType; break; } catch { } } } if (context.Request["outputMimeType"] != null) { sparql.MimeType = context.Request["outputMimeType"]; } TextWriter writer = new StreamWriter(buffer, System.Text.Encoding.UTF8); RunQuery(sparql, source, writer); writer.Flush(); if (context.Request["outputMimeType"] == null || context.Request["outputMimeType"].Trim() == "") { context.Response.ContentType = sparql.MimeType; } else { context.Response.ContentType = context.Request["outputMimeType"]; } context.Response.OutputStream.Write(buffer.GetBuffer(), 0, (int)buffer.Length); } finally { if (closeAfterQuery && source is IDisposable) { ((IDisposable)source).Dispose(); } } } catch (QueryFormatException e) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = 400; context.Response.StatusDescription = e.Message; context.Response.Write(e.Message); if (Debug) { Console.Error.WriteLine(e); Console.Error.WriteLine(); } } catch (QueryExecutionException e) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = 500; context.Response.StatusDescription = e.Message; context.Response.Write(e.Message); if (Debug) { Console.Error.WriteLine(e); Console.Error.WriteLine(); } } }
public void Describe(SelectableSource source, StatementSink sink) { if (!(query is DescribeQuery)) throw new InvalidOperationException("Only DESCRIBE queries are supported by this method (" + query.GetType() + ")."); DescribeQuery q = (DescribeQuery)query; RdfSourceWrapper sourcewrapper = BindLogic(source); try { RdfGraph graph = q.execute(sourcewrapper); WriteGraph(graph, sourcewrapper, sink); } catch (name.levering.ryan.sparql.common.QueryException e) { throw new QueryExecutionException("Error executing query: " + e.Message, e); } }
private static void EulerQuery (SelectableSource source, string rules, Statement[] queries) { Store store = new Store (source); Euler engine = new Euler(new N3Reader(new StringReader(rules))); foreach (Proof p in engine.Prove (store, queries)) { foreach (Statement s in p.Proved) Console.WriteLine(s); } }
public void Describe(SelectableSource source, TextWriter output) { using (RdfWriter w = RdfWriter.Create(MimeType, output)) Describe(source, w); }
public override void Run(SelectableSource source, QueryResultSink resultsink) { if (!(query is SelectQuery)) throw new InvalidOperationException("Only SELECT queries are supported by this method (" + query.GetType() + ")."); // Perform the query SelectQuery squery = (SelectQuery)query; RdfSourceWrapper sourcewrapper = BindLogic(source); RdfBindingSet results; try { results = squery.execute(sourcewrapper); } catch (name.levering.ryan.sparql.common.QueryException e) { throw new QueryExecutionException("Error executing query: " + e.Message, e); } // Prepare binding objects java.util.List vars = results.getVariables(); SparqlVariable[] svars = new SparqlVariable[vars.size()]; SemWebVariable[] vars2 = new SemWebVariable[vars.size()]; for (int i = 0; i < svars.Length; i++) { svars[i] = (SparqlVariable)vars.get(i); vars2[i] = new SemWebVariable(svars[i].getName()); } // Initialize the result sink resultsink.Init(vars2); // set distinct and ordered // Set the comments resultsink.AddComments(queryString + "\n"); resultsink.AddComments(sourcewrapper.GetLog()); // Iterate the bindings java.util.Iterator iter = results.iterator(); long ctr = -1, ctr2 = 0; while (iter.hasNext()) { RdfBindingRow row = (RdfBindingRow)iter.next(); // Since SPARQL processing may be lazy-delayed, // add any new comments that might have been logged. resultsink.AddComments(sourcewrapper.GetLog()); ctr++; if (ctr < ReturnStart && ReturnStart != -1) continue; Resource[] bindings = new Resource[vars2.Length]; for (int i = 0; i < bindings.Length; i++) { Resource r = sourcewrapper.ToResource(row.getValue(svars[i])); r = sourcewrapper.Persist(r); bindings[i] = r; } resultsink.AddComments(sourcewrapper.GetLog()); resultsink.Add(new VariableBindings(vars2, bindings)); ctr2++; if (ctr2 >= ReturnLimit && ReturnLimit != -1) break; } resultsink.AddComments(sourcewrapper.GetLog()); // Close the result sink. resultsink.Finished(); }
public void Select(SelectableSource source, TextWriter output) { QueryResultSink sink; if (MimeType == SparqlXmlQuerySink.MimeType || MimeType == "text/xml") sink = new SparqlXmlQuerySink(output); //else if (MimeType == "text/html") // sink = new HTMLQuerySink(output); //else if (MimeType == "text/csv") // sink = new CSVQuerySink(output); else throw new InvalidOperationException("MIME type not supported."); Select(source, sink); }
public abstract bool Distinct { get; } // assume targetModel.Distinct is true, *then* would Select be distinct? public void Select(Statement template, SelectableSource targetModel, StatementSink sink) { Select(new SelectFilter(template), targetModel, sink); }
public void Select(SelectableSource source, QueryResultSink sink) { if (!(query is SelectQuery)) throw new InvalidOperationException("Only SELECT queries are supported by this method (" + query.GetType() + ")."); Run(source, sink); }
public abstract MetaQueryResult MetaQuery(Statement[] graph, QueryOptions options, SelectableSource targetModel);
/* INTERNAL METHODS TO CONTROL QUERY EXECUTION */ private RdfSourceWrapper BindLogic(SelectableSource source) { RdfSourceWrapper sourcewrapper = new RdfSourceWrapper(source, this); MyLogicFactory logic = new MyLogicFactory(); foreach (RdfFunction f in extFunctions) logic.registerExternalFunction( new URIWrapper(f.Uri), new ExtFuncWrapper(sourcewrapper, f)); query.prepare(sourcewrapper, logic); return sourcewrapper; }
public override void Select(SelectFilter filter, SelectableSource targetModel, StatementSink sink) { targetModel.Select(filter, sink); }
public override void Query(Statement[] graph, SemWeb.Query.QueryOptions options, SelectableSource targetModel, QueryResultSink result) { SemWeb.Query.GraphMatch q = new SemWeb.Query.GraphMatch(); foreach (Statement s in graph) q.AddGraphStatement(s); q.ReturnLimit = options.Limit; if (options.VariableKnownValues != null) { #if !DOTNET2 foreach (DictionaryEntry ent in options.VariableKnownValues) q.SetVariableRange((Variable)ent.Key, (ICollection)ent.Value); #else foreach (KeyValuePair<Variable,ICollection<Resource>> ent in options.VariableKnownValues) q.SetVariableRange(ent.Key, ent.Value); #endif } if (options.VariableLiteralFilters != null) { #if !DOTNET2 foreach (DictionaryEntry ent in options.VariableLiteralFilters) foreach (LiteralFilter filter in (ICollection)ent.Value) q.AddLiteralFilter((Variable)ent.Key, filter); #else foreach (KeyValuePair<Variable,ICollection<LiteralFilter>> ent in options.VariableLiteralFilters) foreach (LiteralFilter filter in ent.Value) q.AddLiteralFilter(ent.Key, filter); #endif } if (options.DistinguishedVariables != null) { foreach (Variable v in options.DistinguishedVariables) q.SetDistinguishedVariable(v); } q.Run(targetModel, result); }
public RdfSourceWrapper(SelectableSource source, SparqlEngine sparql) { this.source = source; this.sparql = sparql; }