public void AddTripleWithUriSubject(string subject, string predicate, string obj) { UriNode subj = myGraph.CreateUriNode(new Uri(subject)); UriNode pred = myGraph.CreateUriNode(new Uri(predicate)); myGraph.Assert(new Triple(subj, pred, myGraph.CreateUriNode(new Uri(obj)))); }
public void SELECTUnionOrderByClauses() { var expectedQuery = "SELECT ?uri, ?label WHERE {{ ?uri <http://www.w3.org/2000/01/rdf-schema#label> ?label } {<http://dbpedia.org/resource/Paris> <http://www.w3.org/2000/01/rdf-schema#label> ?label} UNION {<http://dbpedia.org/resource/Montreal> <http://www.w3.org/2000/01/rdf-schema#label> ?label}} ORDER BY ASC(?label)"; var subject = new UriNode("http://dbpedia.org/resource/Paris"); var predicate = new UriNode("http://www.w3.org/2000/01/rdf-schema#label"); var obj = new VariableNode("label"); var triple = new Triple(subject, predicate, obj); var triples = new List <Triple> { triple }; subject = new UriNode("http://dbpedia.org/resource/Montreal"); triple = new Triple(subject, predicate, obj); triples.Add(triple); var unionClause = new dotNetSPARQL.Query.UnionClause(triples); triple = new Triple( new VariableNode("uri"), new UriNode("http://www.w3.org/2000/01/rdf-schema#label"), new VariableNode("label")); var orderByClause = new dotNetSPARQL.Query.OrderByClause("label"); var select = new dotNetSPARQL.Query.Select(new List <Triple>() { triple }, new dotNetSPARQL.Query.BaseClause[] { orderByClause, unionClause }, new string[] { "uri", "label" }); Assert.AreEqual(expectedQuery, select.ToString()); }
public static RailService CreateFromNode(UriNode _service) { RailService result = new RailService(_service); result.txtName.Text = _service.ToDisplayString(); return(result); }
public void addTripleWithLiteralSubject(string subject, string predicate, string obj, string language) { UriNode subj = myGraph.CreateUriNode(new Uri(subject)); UriNode pred = myGraph.CreateUriNode(new Uri(predicate)); myGraph.Assert(new Triple(subj, pred, myGraph.CreateLiteralNode(obj, language))); }
public static IEnumerable <Triple> GetContextualGraph(this IGraph graph, UriNode uriNode, HashSet <string> processed, int rank) { if (rank == 0) { return(Enumerable.Empty <Triple>()); } processed.Add(uriNode.ToString()); rank--; var triples = graph.GetTriples(uriNode).ToList(); var triplesToAdd = new List <Triple>(); foreach (var triple in triples) { var subject = triple.Subject.NodeType == NodeType.Uri ? (UriNode)triple.Subject : null; if (!processed.Contains(subject.ToString())) { processed.Add(subject.ToString()); triplesToAdd.AddRange(GetContextualGraph(graph, subject, processed, rank)); } var obj = triple.Object.NodeType == NodeType.Uri ? (UriNode)triple.Object : null; if (obj != null && !processed.Contains(obj.ToString())) { processed.Add(obj.ToString()); triplesToAdd.AddRange(GetContextualGraph(graph, obj, processed, rank)); } } triples.AddRange(triplesToAdd); return(triples.Distinct()); }
/// <summary> /// Gets the list of Search Results which match the given search term /// </summary> /// <param name="text">Search Term</param> /// <param name="callback">Callback to invoke when the operation completes</param> /// <param name="state">State to pass to the callback</param> public void Search(String text, PelletSearchServiceCallback callback, Object state) { String search = this._searchUri + "?search=" + Uri.EscapeDataString(text); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); request.Method = this.Endpoint.HttpMethods.First(); request.Accept = "text/json"; #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif String jsonText; JArray json; request.BeginGetResponse(result => { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result)) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd(); json = JArray.Parse(jsonText); response.Close(); //Parse the Response into Search Results List <SearchServiceResult> results = new List <SearchServiceResult>(); foreach (JToken res in json.Children()) { JToken hit = res.SelectToken("hit"); String type = (String)hit.SelectToken("type"); INode node; if (type.ToLower().Equals("uri")) { node = new UriNode(null, UriFactory.Create((String)hit.SelectToken("value"))); } else { node = new BlankNode(null, (String)hit.SelectToken("value")); } double score = (double)res.SelectToken("score"); results.Add(new SearchServiceResult(node, score)); } callback(results, state); } }, null); }
/// <summary>Create new <see cref="Quad"/>.</summary> public Quad(Node <UriOrBlank> graph, Node <UriOrBlank> subject, UriNode predicate, Node @object) { Graph = graph; Subject = subject; Predicate = predicate; Object = @object; }
/// <summary>Create an new <see cref="RdfsList"/>.</summary> public RdfsList(INodeFactory f, Graph owner) { _f = f; _owner = owner; _first = f.Uri(RDFS.First); _next = f.Uri(RDFS.Rest); _nil = f.Uri(RDFS.Nil); }
/// <inheritdoc/> public IRdfData Assert(Node <UriOrBlank> graph, Node <UriOrBlank> sub, UriNode predicate, Node val , out Quad quad) { quad = new Quad(graph, sub, predicate, val); _data.Add(quad); return(this); }
/// <inheritdoc /> public IRdfData Assert(Node <UriOrBlank> graph, Node <UriOrBlank> sub, UriNode predicate, Node val, out Quad q) { lock (_locker) { _inner.Assert(graph, sub, predicate, val, out q); return(this); } }
private void button1_Click(object sender, RoutedEventArgs e) { /* Connect To DBPedia * //First define a SPARQL Endpoint for DBPedia * SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql")); * * //Next define our query * //We're going to ask DBPedia to describe the first thing it finds which is a Person * String query = "DESCRIBE ?person WHERE {?person a <http://dbpedia.org/ontology/Person>} LIMIT 1"; * * //Get the result * Graph g = endpoint.QueryWithResultGraph(query); * * FastRdfXmlWriter rxtw = new FastRdfXmlWriter(); * rxtw.Save(g, "dbp.txt");*/ Graph g = new Graph(); UriNode omid = g.CreateUriNode(new Uri("http://www.omidey.co.cc")); UriNode says = g.CreateUriNode(new Uri("http://www.sample.com/says")); LiteralNode hello = g.CreateLiteralNode("Hello World!!!"); LiteralNode sallam = g.CreateLiteralNode("Sallam 2nyaaa!!!", "fa"); g.Assert(new Triple(omid, says, hello)); g.Assert(new Triple(omid, says, sallam)); //foreach (Triple t in g.Triples) //{ // MessageBox.Show(t.ToString()); //} String query = "SELECT ?n ?p WHERE {?n ?p 'Hello World!!!'}"; // like select * => "SELECT ?n ?p ?m WHERE {?n ?p ?m}" SparqlResultSet res = (SparqlResultSet)g.ExecuteQuery(query); foreach (SparqlResult r in res) { MessageBox.Show(r.ToString()); } FastRdfXmlWriter rxtw = new FastRdfXmlWriter(); rxtw.Save(g, "omid.txt"); //TripleStore ts = new TripleStore(); //Object res = ts.ExecuteQuery("SELECT * WHERE {?s ?p ?o}"); //if (res is SparqlResultSet) //{ // SparqlResultSet results = (SparqlResultSet)res; // foreach (SparqlResult sr in results) // { // Console.WriteLine(sr.ToString()); // } //} }
/// <summary>Read the first Node of type <typeparamref name="T"/></summary> /// <exception cref="TypeMustNotBeANode"></exception> public static IReadOnlyList <Quad> ValueOptional <T>(this IEnumerable <Quad> self, UriNode predicate, out Node <T>?data) where T : notnull { var ro = self.Ro(); data = ro.FirstOrNull(x => x.Predicate == predicate && x.Object is Node <T>)?.Object as Node <T>; return(ro); }
public RdfDataFetcher(IRdfData rdf) { _rdf = rdf; BackingFile = _rdf.Uri("sys:/backingFile"); if (!_rdf.Stats().Mappings.Any(x => x is FileInfoNodeMap)) { throw new Exception( $"Must include node map {nameof(FileInfoNodeMap)}"); } }
/// <summary>Read the first <typeparamref name="T"/> value.</summary> /// <exception cref="TypeMustNotBeANode"></exception> /// <exception cref="ValueNotFoundError"></exception> public static IReadOnlyList <Quad> Value <T>(this IEnumerable <Quad> self, UriNode predicate, out T data) where T : notnull { var ro = self.Ro(); data = ro.FirstOrNull(x => x.Predicate == predicate && x.Object is Node <T>)?.Object is Node <T> node ? node.Value : throw new ValueNotFoundError(); return(ro); }
public void SELECTPredicateVariableNoLimit() { var expectedQuery = "SELECT DISTINCT ?predicate WHERE { <http://dbpedia.org/resource/Family_Guy> ?predicate <http://dbpedia.org/resource/Seth_MacFarlane> }"; var subject = new UriNode(new Uri("http://dbpedia.org/resource/Family_Guy")); var predicate = new VariableNode("predicate"); var obj = new UriNode(new Uri("http://dbpedia.org/resource/Seth_MacFarlane")); var triple = new Triple(subject, predicate, obj); var query = new dotNetSPARQL.Query.Select(triple, "predicate", true); Assert.AreEqual(expectedQuery, query.ToString()); }
public void ASKObjectVariable() { var expectedQuery = "ASK WHERE { <http://dbpedia.org/resource/Family_Guy> <http://dbpedia.org/ontology/author> ?uri }"; var subject = new UriNode("http://dbpedia.org/resource/Family_Guy"); var predicate = new UriNode("http://dbpedia.org/ontology/author"); var obj = new VariableNode("uri"); var triple = new Triple(subject, predicate, obj); var query = new dotNetSPARQL.Query.Ask(triple); Assert.AreEqual(expectedQuery, query.ToString()); }
public void ASKPredicateVariable() { var expectedQuery = "ASK WHERE { <http://dbpedia.org/resource/Family_Guy> ?predicate <http://dbpedia.org/resource/Seth_MacFarlane> }"; var subject = new UriNode("http://dbpedia.org/resource/Family_Guy"); var predicate = new VariableNode("predicate"); var obj = new UriNode("http://dbpedia.org/resource/Seth_MacFarlane"); var triple = new Triple(subject, predicate, obj); var query = new dotNetSPARQL.Query.Ask(triple); Assert.AreEqual(expectedQuery, query.ToString()); }
public void SELECTSubjectVariableNoLimit() { var expectedQuery = "SELECT DISTINCT ?subject WHERE { ?subject <http://dbpedia.org/ontology/author> <http://dbpedia.org/resource/Seth_MacFarlane> }"; var subject = new VariableNode("subject"); var predicate = new UriNode(new Uri("http://dbpedia.org/ontology/author")); var obj = new UriNode(new Uri("http://dbpedia.org/resource/Seth_MacFarlane")); var triple = new Triple(subject, predicate, obj); var query = new dotNetSPARQL.Query.Select(triple, "subject", true); Assert.AreEqual(expectedQuery, query.ToString()); }
public void SELECTObjectVariableNoLimit() { var expectedQuery = "SELECT DISTINCT ?uri WHERE { <http://dbpedia.org/resource/Paris> <http://dbpedia.org/ontology/mayor> ?uri }"; var subject = new UriNode(new Uri("http://dbpedia.org/resource/Paris")); var predicate = new UriNode(new Uri("http://dbpedia.org/ontology/mayor")); var obj = new VariableNode("uri"); var triple = new Triple(subject, predicate, obj); var query = new dotNetSPARQL.Query.Select(triple, "uri", true); Assert.AreEqual(expectedQuery, query.ToString()); }
public void ASKChainedQuery() { var expectedQuery = "ASK WHERE { <http://dbpedia.org/resource/Family_Guy> <http://dbpedia.org/ontology/author> ?uri . ?uri <http://dbpedia.org/ontology/birthPlace> ?obj }"; var subject = new UriNode("http://dbpedia.org/resource/Family_Guy"); var predicate = new UriNode("http://dbpedia.org/ontology/author"); var obj = new VariableNode("uri"); var firstTriple = new Triple(subject, predicate, obj); var secondTriple = new Triple(obj, new UriNode("http://dbpedia.org/ontology/birthPlace"), new VariableNode("obj")); var query = new dotNetSPARQL.Query.Ask(new List <Triple>() { firstTriple, secondTriple }); Assert.AreEqual(expectedQuery, query.ToString()); }
public void SELECTPredicateObjectVariableLimit100() { var expectedQuery = "SELECT DISTINCT ?predicate, ?object WHERE { <http://dbpedia.org/resource/Family_Guy> ?predicate ?object } LIMIT 100"; var subject = new UriNode(new Uri("http://dbpedia.org/resource/Family_Guy")); var predicate = new VariableNode("predicate"); var obj = new VariableNode("object"); var triple = new Triple(subject, predicate, obj); var variables = new string[] { "predicate", "object" }; var query = new dotNetSPARQL.Query.Select(new List <Triple> { triple }, variables, true, 100); Assert.AreEqual(expectedQuery, query.ToString()); }
public void SELECTSubjectPredicateVariableNoLimit() { var expectedQuery = "SELECT DISTINCT ?subject, ?predicate WHERE { ?subject ?predicate <http://dbpedia.org/resource/Paris> }"; var subject = new VariableNode("subject"); var predicate = new VariableNode("predicate"); var obj = new UriNode(new Uri("http://dbpedia.org/resource/Paris")); var triple = new Triple(subject, predicate, obj); var variables = new string[] { "subject", "predicate" }; var query = new dotNetSPARQL.Query.Select(new List <Triple> { triple }, variables, true); Assert.AreEqual(expectedQuery, query.ToString()); }
public static string ToDisplayString(this UriNode node) { IEnumerable <Triple> labels = node.Graph.GetTriplesWithSubjectPredicate(node, node.Graph.CreateUriNode(UriFactory.Create(Properties.Settings.Default.Label)) ); if (labels.Any()) { Triple firstLabel = labels.First(); ILiteralNode labelNode = firstLabel.Object as ILiteralNode; return(labelNode.Value); } else { return(node.Uri.Segments[node.Uri.Segments.Count() - 1]); } }
public void SELECTMultipleTriples() { var expectedQuery = "SELECT DISTINCT ?object WHERE { <http://dbpedia.org/resource/Family_Guy> <http://dbpedia.org/ontology/author> ?uri . ?uri <http://dbpedia.org/ontology/birthPlace> ?object }"; var subject = new UriNode("http://dbpedia.org/resource/Family_Guy"); var predicate = new VariableNode("predicate"); var obj = new VariableNode("object"); var firstTriple = new Triple(new UriNode("http://dbpedia.org/resource/Family_Guy"), new UriNode("http://dbpedia.org/ontology/author"), new VariableNode("uri")); var secondTriple = new Triple(new VariableNode("uri"), new UriNode("http://dbpedia.org/ontology/birthPlace"), new VariableNode("object")); var variables = new string[] { "object" }; var query = new dotNetSPARQL.Query.Select(new List <Triple> { firstTriple, secondTriple }, variables, true); Assert.AreEqual(expectedQuery, query.ToString()); }
public void UNIONClause() { var expectedQuery = "{<http://dbpedia.org/resource/Paris> <http://www.w3.org/2000/01/rdf-schema#label> ?label} UNION {<http://dbpedia.org/resource/Montreal> <http://www.w3.org/2000/01/rdf-schema#label> ?label}"; var subject = new UriNode("http://dbpedia.org/resource/Paris"); var predicate = new UriNode("http://www.w3.org/2000/01/rdf-schema#label"); var obj = new VariableNode("label"); var triple = new Triple(subject, predicate, obj); var triples = new List <Triple> { triple }; subject = new UriNode("http://dbpedia.org/resource/Montreal"); triple = new Triple(subject, predicate, obj); triples.Add(triple); var unionClause = new dotNetSPARQL.Query.UnionClause(triples); Assert.AreEqual(expectedQuery, unionClause.ToString()); }
public void ORDERBYQuery() { var expectedQuery = "SELECT WHERE { <http://dbpedia.org/resource/Paris> <http://dbpedia.org/ontology/wikiPageExternalLink> ?uri } ORDER BY DESC(?uri)"; var subject = new UriNode("http://dbpedia.org/resource/Paris"); var predicate = new UriNode("http://dbpedia.org/ontology/wikiPageExternalLink"); var obj = new VariableNode("uri"); var triple = new Triple(subject, predicate, obj); var orderByClause = new dotNetSPARQL.Query.OrderByClause("uri", true); var clauses = new dotNetSPARQL.Query.BaseClause[] { orderByClause }; var triples = new List <Triple> { triple }; var selectCountQuery = new dotNetSPARQL.Query.Select( triples, clauses, new string[0]); Assert.AreEqual(expectedQuery, selectCountQuery.ToString()); }
public void TestVocab() { //TODO: this is a bit nasty think about it (perhaps the method return nodes and then the graph does the adding??) var gn = new PredicateNet("p:", new Uri("http://test.com/places/"), (uri, graph) => { var net = graph as PredicateNet; graph.Add("p:name", "http://www.w3.org/2000/01/rdf-schema#domain", "p:Place"); graph.Add("p:code", "http://www.w3.org/2000/01/rdf-schema#domain", "p:Place"); graph.Add("p:flag", "http://www.w3.org/2000/01/rdf-schema#domain", "p:Country"); graph.Add("p:mayor", "http://www.w3.org/2000/01/rdf-schema#domain", "p:City"); graph.Add("p:Country", "http://www.w3.org/2000/01/rdf-schema#subClassof", "p:Place"); graph.Add("p:City", "http://www.w3.org/2000/01/rdf-schema#subClassof", "p:Place"); net.Add(net.GetPrefixNamespaceNode(), net.Node("has"), graph.Node("p:name")); net.Add(net.GetPrefixNamespaceNode(), net.Node("has"), graph.Node("p:code")); net.Add(net.GetPrefixNamespaceNode(), net.Node("has"), graph.Node("p:flag")); net.Add(net.GetPrefixNamespaceNode(), net.Node("has"), graph.Node("p:mayor")); }); gn.MaxNumberOfPaths = 5; //gn.MaxPathLenght = 10; gn.TrainFromQueries( "select * where { ?s a p:City . ?s p:mayor ?mayor }", "select * where { ?x a p:City . ?x p:mayor 'ted' }", //TODO: this should not throw the prediction off "select * where { ?s a p:City . ?s p:name ?name }", "select * where { ?s a p:Country . ?s p:flag ?flag }", "select * where { ?x a p:Country . ?x p:flag 'xxx' }" ); //var cityQuery = new Node("select *"); var city = new UriNode("?x"); city.UseEdgesAsInterface = false; //cityQuery.AddEdge("next", city, gn); city.AddEdge(new UriNode("a"), new UriNode("http://test.com/places/City")); Assert.AreEqual("mayor", gn.Predict(city)); //var countryQuery = new Node("select *"); var country = new UriNode("?x"); country.UseEdgesAsInterface = false; //countryQuery.AddEdge("next", country, gn); country.AddEdge(new UriNode("a"), new UriNode("http://test.com/places/Country")); Assert.AreEqual("flag", gn.Predict(country)); }
public static IEnumerable <Triple> GetMaxContextualGraph(this IGraph graph, UriNode uriNode, HashSet <UriNode> processed) { var triples = graph.GetTriples(uriNode).ToList(); var triplesToAdd = new List <Triple>(); foreach (var triple in triples) { var subject = triple.Subject.NodeType == NodeType.Uri ? (UriNode)triple.Subject : null; if (!processed.Contains(subject)) { processed.Add(subject); triplesToAdd.AddRange(GetMaxContextualGraph(graph, subject, processed)); } var obj = triple.Object.NodeType == NodeType.Uri ? (UriNode)triple.Object : null; if (obj != null && !processed.Contains(obj)) { processed.Add(obj); triplesToAdd.AddRange(GetMaxContextualGraph(graph, obj, processed)); } } triples.AddRange(triplesToAdd); return(triples.Distinct()); }
public void initGraph() { myGraph = new Graph(); UriNode omid = myGraph.CreateUriNode(new Uri("http://www.omidey.co.cc")); UriNode says = myGraph.CreateUriNode(new Uri("http://www.sample.com/says")); LiteralNode hello = myGraph.CreateLiteralNode("Hello World!!!"); LiteralNode sallam = myGraph.CreateLiteralNode("Sallam 2nyaaa!!!", "fa"); LiteralNode a = myGraph.CreateLiteralNode("A"); // must be uri for being serializable and for that we can save it LiteralNode b = myGraph.CreateLiteralNode("B"); LiteralNode c = myGraph.CreateLiteralNode("C"); LiteralNode aa = myGraph.CreateLiteralNode("omid"); // must be uri for being serializable and for that we can save it LiteralNode bb = myGraph.CreateLiteralNode("hast"); LiteralNode cc = myGraph.CreateLiteralNode("askari"); myGraph.Assert(new Triple(omid, says, hello)); myGraph.Assert(new Triple(omid, says, sallam)); myGraph.Assert(new Triple(a, b, c)); myGraph.Assert(new Triple(aa, bb, cc)); }
/// <summary> /// Selects all Triples where the Subject is a Uri Node with the given Uri from a Subset of Graphs in the Triple Store /// </summary> /// <param name="graphUris">List of the Graph URIs of Graphs you want to select over</param> /// <param name="u">Uri</param> /// <returns></returns> public IEnumerable<Triple> GetTriplesWithSubject(List<Uri> graphUris, Uri u) { IUriNode uri = new UriNode(null, u); IEnumerable<Triple> ts = from g in this._graphs where graphUris.Contains(g.BaseUri) from t in g.Triples where t.HasSubject(uri) select t; return ts; }
/// <summary> /// Selects all Triples which have a Uri Node with the given Uri from a Subset of Graphs in the Triple Store /// </summary> /// <param name="graphUris">List of the Graph URIs of Graphs you want to select over</param> /// <param name="uri">Uri</param> /// <returns></returns> public IEnumerable<Triple> GetTriples(List<Uri> graphUris, Uri uri) { IUriNode u = new UriNode(null, uri); IEnumerable<Triple> ts = from g in this._graphs where graphUris.Contains(g.BaseUri) from t in g.Triples where t.Involves(u) select t; return ts; }
/// <summary> /// Selects all Triples which have a Uri Node with the given Uri from all the Query Triples /// </summary> /// <param name="uri">Uri</param> /// <returns></returns> public IEnumerable<Triple> GetTriples(Uri uri) { IUriNode u = new UriNode(null, uri); return from g in this._graphs from t in g.Triples where t.Involves(u) select t; }
public UriNodeControl(UriNode u) : this(u, new NTriplesFormatter()) { }
private void TryParseCollection(SparqlQueryParserContext context, GraphPattern p, bool nested) { //Check the next Token IToken next = context.Tokens.Peek(); if (next.TokenType == Token.RIGHTBRACKET) { //Empty Collection context.Tokens.Dequeue(); if (!nested) { //Push an rdf:nil Uri on the Stack context.LocalTokens.Push(new UriToken("<" + NamespaceMapper.RDF + "nil>", next.StartLine, next.StartPosition, next.EndPosition)); } } else { //Push a Blank Node Token onto the stack for the start of the collection BlankNodeWithIDToken blank; if (!nested) { blank = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine, next.StartPosition, next.EndPosition); context.LocalTokens.Push(blank); } else { blank = new BlankNodeWithIDToken("_:sparql-autos" + context.BlankNodeID, next.StartLine, next.StartPosition, next.EndPosition); } bool first = true; IUriNode rdfFirst, rdfRest, rdfNil; rdfFirst = new UriNode(null, new Uri(NamespaceMapper.RDF + "first")); rdfRest = new UriNode(null, new Uri(NamespaceMapper.RDF + "rest")); rdfNil = new UriNode(null, new Uri(NamespaceMapper.RDF + "nil")); do { next = context.Tokens.Peek(); switch (next.TokenType) { case Token.BLANKNODE: case Token.BLANKNODEWITHID: case Token.KEYWORDA: case Token.LITERAL: case Token.LONGLITERAL: case Token.PLAINLITERAL: case Token.QNAME: case Token.URI: case Token.VARIABLE: //Create the Triple pattern if (first) { //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, next))); first = false; } else { //Get new Blank Node ID BlankNodeWithIDToken blank2 = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine,next.StartPosition,next.EndPosition); //rdf:rest Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfRest), this.TryCreatePatternItem(context, blank2))); blank = blank2; //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, next))); } break; case Token.LEFTSQBRACKET: //Is the next token a Right Square Bracket? //ie. a [] for an anonymous blank node context.Tokens.Dequeue(); next = context.Tokens.Peek(); if (next.TokenType == Token.RIGHTSQBRACKET) { BlankNodeWithIDToken anon = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine, next.StartPosition, next.EndPosition); if (first) { //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, anon))); first = false; } else { //Get new Blank Node ID BlankNodeWithIDToken blank2 = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine, next.StartPosition, next.EndPosition); //rdf:rest Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfRest), this.TryCreatePatternItem(context, blank2))); blank = blank2; //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, anon))); } } else { BlankNodeWithIDToken anon = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine, next.StartPosition, next.EndPosition); if (first) { //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, anon))); first = false; } else { //Get new Blank Node ID BlankNodeWithIDToken blank2 = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine, next.StartPosition, next.EndPosition); //rdf:rest Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfRest), this.TryCreatePatternItem(context, blank2))); blank = blank2; //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, anon))); } //Parse the Blank Node Collection context.LocalTokens.Push(anon); this.TryParsePredicateObjectList(context, p, context.LocalTokens.Count + 1); continue; } break; case Token.LEFTBRACKET: BlankNodeWithIDToken innerCollection = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine, next.StartPosition, next.EndPosition); if (first) { //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, innerCollection))); first = false; } else { //Get new Blank Node ID BlankNodeWithIDToken blank2 = new BlankNodeWithIDToken(context.GetNewBlankNodeID(), next.StartLine, next.StartPosition, next.EndPosition); //rdf:rest Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfRest), this.TryCreatePatternItem(context, blank2))); blank = blank2; //rdf:first Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfFirst), this.TryCreatePatternItem(context, innerCollection))); } context.Tokens.Dequeue(); this.TryParseCollection(context, p, true); continue; case Token.RIGHTBRACKET: //End of Collection //rdf:rest Pattern p.AddTriplePattern(new TriplePattern(this.TryCreatePatternItem(context, blank), new NodeMatchPattern(rdfRest), new NodeMatchPattern(rdfNil))); break; default: throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered while trying to parse a Collection", next); } context.Tokens.Dequeue(); } while (next.TokenType != Token.RIGHTBRACKET); } }
/// <summary> /// Copies a Node so it can be used in another Graph since by default Triples cannot contain Nodes from more than one Graph /// </summary> /// <param name="original">Node to Copy</param> /// <param name="target">Graph to Copy into</param> /// <returns></returns> /// <remarks> /// <para> /// <strong>Warning:</strong> Copying Blank Nodes may lead to unforseen circumstances since no remapping of IDs between Graphs is done /// </para> /// </remarks> public static INode CopyNode(INode original, IGraph target) { //No need to copy if it's already in the relevant Graph if (ReferenceEquals(original.Graph, target)) return original; if (original.NodeType == NodeType.Uri) { IUriNode u = (IUriNode)original; IUriNode u2 = new UriNode(target, u.Uri); return u2; } else if (original.NodeType == NodeType.Literal) { ILiteralNode l = (ILiteralNode)original; ILiteralNode l2; if (l.Language.Equals(String.Empty)) { if (!(l.DataType == null)) { l2 = new LiteralNode(target, l.Value, l.DataType); } else { l2 = new LiteralNode(target, l.Value); } } else { l2 = new LiteralNode(target, l.Value, l.Language); } return l2; } else if (original.NodeType == NodeType.Blank) { IBlankNode b = (IBlankNode)original; IBlankNode b2; b2 = new BlankNode(target, b.InternalID); return b2; } else if (original.NodeType == NodeType.Variable) { IVariableNode v = (IVariableNode)original; return new VariableNode(target, v.VariableName); } else { throw new RdfException("Unable to Copy '" + original.GetType().ToString() + "' Nodes between Graphs"); } }
/// <summary> /// Returns the UriNode with the given QName if it exists /// </summary> /// <param name="qname">The QName of the Node to select</param> /// <returns></returns> public override IUriNode GetUriNode(String qname) { IUriNode test = new UriNode(this, qname); IEnumerable<IUriNode> us = from u in this._nodes.UriNodes where u.Equals(test) select u; return us.FirstOrDefault(); }
private Uri TryParseContext(ITokenQueue tokens) { IToken next = tokens.Dequeue(); if (next.TokenType == Token.DOT) { return null; } else { INode context; switch (next.TokenType) { case Token.BLANKNODEWITHID: context = new BlankNode(null, next.Value.Substring(2)); break; case Token.URI: context = new UriNode(null, new Uri(next.Value)); break; case Token.LITERAL: //Check for Datatype/Language IToken temp = tokens.Peek(); if (temp.TokenType == Token.LANGSPEC) { tokens.Dequeue(); context = new LiteralNode(null, next.Value, temp.Value); } else if (temp.TokenType == Token.DATATYPE) { tokens.Dequeue(); context = new LiteralNode(null, next.Value, new Uri(temp.Value.Substring(1, temp.Value.Length - 2))); } else { context = new LiteralNode(null, next.Value); } break; default: throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a Blank Node/Literal/URI as the Context of the Triple", next); } //Ensure we then see a . to terminate the Quad next = tokens.Dequeue(); if (next.TokenType != Token.DOT) { throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a Dot Token (Line Terminator) to terminate a Triple", next); } //Finally return the Context URI if (context.NodeType == NodeType.Uri) { return ((IUriNode)context).Uri; } else if (context.NodeType == NodeType.Blank) { return new Uri("nquads:bnode:" + context.GetHashCode()); } else if (context.NodeType == NodeType.Literal) { return new Uri("nquads:literal:" + context.GetHashCode()); } else { throw ParserHelper.Error("Cannot turn a Node of type '" + context.GetType().ToString() + "' into a Context URI for a Triple", next); } } }
/// <summary> /// Gets the list of Search Results which match the given search term /// </summary> /// <param name="text">Search Term</param> /// <returns>A list of Search Results representing Nodes in the Knowledge Base that match the search term</returns> public List<SearchServiceResult> Search(String text) { String search = this._searchUri + "?search=" + Uri.EscapeDataString(text); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); request.Method = this.Endpoint.HttpMethods.First(); request.Accept = "text/json"; #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif String jsonText; JArray json; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd(); json = JArray.Parse(jsonText); response.Close(); } //Parse the Response into Search Results try { List<SearchServiceResult> results = new List<SearchServiceResult>(); foreach (JToken result in json.Children()) { JToken hit = result.SelectToken("hit"); String type = (String)hit.SelectToken("type"); INode node; if (type.ToLower().Equals("uri")) { node = new UriNode(null, new Uri((String)hit.SelectToken("value"))); } else { node = new BlankNode(null, (String)hit.SelectToken("value")); } double score = (double)result.SelectToken("score"); results.Add(new SearchServiceResult(node, score)); } return results; } catch (WebException webEx) { #if DEBUG if (Options.HttpDebugging) { if (webEx.Response != null) Tools.HttpDebugResponse((HttpWebResponse)webEx.Response); } #endif throw new RdfReasoningException("A HTTP error occurred while communicating with Pellet Server", webEx); } catch (Exception ex) { throw new RdfReasoningException("Error occurred while parsing Search Results from the Search Service", ex); } }
/// <summary> /// Evaluates the Graph Clause by setting up the dataset, applying the pattern and then generating additional bindings if necessary /// </summary> /// <param name="context">Evaluation Context</param> /// <returns></returns> public BaseMultiset Evaluate(SparqlEvaluationContext context) { // Q: Can we optimise GRAPH when the input is the Null Multiset to just return the Null Multiset? bool datasetOk = false; try { List <String> activeGraphs = new List <string>(); // Get the URIs of Graphs that should be evaluated over if (_graphSpecifier.TokenType != Token.VARIABLE) { switch (_graphSpecifier.TokenType) { case Token.URI: case Token.QNAME: Uri activeGraphUri = UriFactory.Create(Tools.ResolveUriOrQName(_graphSpecifier, context.Query.NamespaceMap, context.Query.BaseUri)); if (context.Data.HasGraph(activeGraphUri)) { // If the Graph is explicitly specified and there are FROM/FROM NAMED present then the Graph // URI must be in the graphs specified by a FROM/FROM NAMED or the result is null if (context.Query == null || ((!context.Query.DefaultGraphs.Any() && !context.Query.NamedGraphs.Any()) || context.Query.NamedGraphs.Any(u => EqualityHelper.AreUrisEqual(activeGraphUri, u))) ) { // Either there was no Query // OR there were no Default/Named Graphs (hence any Graph URI is permitted) // OR the specified URI was a Named Graph URI // In any case we can go ahead and set the active Graph activeGraphs.Add(activeGraphUri.AbsoluteUri); } else { // The specified URI was not present in the Named Graphs so return null context.OutputMultiset = new NullMultiset(); return(context.OutputMultiset); } } else { // If specifies a specific Graph and not in the Dataset result is a null multiset context.OutputMultiset = new NullMultiset(); return(context.OutputMultiset); } break; default: throw new RdfQueryException("Cannot use a '" + _graphSpecifier.GetType().ToString() + "' Token to specify the Graph for a GRAPH clause"); } } else { String gvar = _graphSpecifier.Value.Substring(1); // Watch out for the case in which the Graph Variable is not bound for all Sets in which case // we still need to operate over all Graphs if (context.InputMultiset.ContainsVariable(gvar) && context.InputMultiset.Sets.All(s => s[gvar] != null)) { // If there are already values bound to the Graph variable for all Input Solutions then we limit the Query to those Graphs List <Uri> graphUris = new List <Uri>(); foreach (ISet s in context.InputMultiset.Sets) { INode temp = s[gvar]; if (temp == null) { continue; } if (temp.NodeType != NodeType.Uri) { continue; } activeGraphs.Add(temp.ToString()); graphUris.Add(((IUriNode)temp).Uri); } } else { // Nothing yet bound to the Graph Variable so the Query is over all the named Graphs if (context.Query != null && context.Query.NamedGraphs.Any()) { // Query specifies one/more named Graphs activeGraphs.AddRange(context.Query.NamedGraphs.Select(u => u.AbsoluteUri)); } else if (context.Query != null && context.Query.DefaultGraphs.Any() && !context.Query.NamedGraphs.Any()) { // Gives null since the query dataset does not include any named graphs context.OutputMultiset = new NullMultiset(); return(context.OutputMultiset); } else { // Query is over entire dataset/default Graph since no named Graphs are explicitly specified activeGraphs.AddRange(context.Data.GraphUris.Select(u => u.ToSafeString())); } } } // Remove all duplicates from Active Graphs to avoid duplicate results activeGraphs = activeGraphs.Distinct().ToList(); // Evaluate the inner pattern BaseMultiset initialInput = context.InputMultiset; BaseMultiset finalResult = new Multiset(); // Evalute for each Graph URI and union the results foreach (String uri in activeGraphs) { // Always use the same Input for each Graph URI and set that Graph to be the Active Graph // Be sure to translate String.Empty back to the null URI to select the default graph // correctly context.InputMultiset = initialInput; Uri currGraphUri = (uri.Equals(String.Empty)) ? null : UriFactory.Create(uri); // Set Active Graph if (currGraphUri == null) { // GRAPH operates over named graphs only so default graph gets skipped continue; } // The result of the HasGraph() call is ignored we just make it so datasets with any kind of // load on demand behaviour work properly context.Data.HasGraph(currGraphUri); // All we actually care about is setting the active graph context.Data.SetActiveGraph(currGraphUri); datasetOk = true; // Evaluate for the current Active Graph BaseMultiset result = context.Evaluate(_pattern); // Merge the Results into our overall Results if (result is NullMultiset) { // Don't do anything, adds nothing to the results } else if (result is IdentityMultiset) { // Adds a single row to the results if (_graphSpecifier.TokenType == Token.VARIABLE) { // Include graph variable if not yet bound INode currGraph = new UriNode(null, currGraphUri); Set s = new Set(); s.Add(_graphSpecifier.Value.Substring(1), currGraph); finalResult.Add(s); } else { finalResult.Add(new Set()); } } else { // If the Graph Specifier is a Variable then we must either bind the // variable or eliminate solutions which have an incorrect value for it if (_graphSpecifier.TokenType == Token.VARIABLE) { String gvar = _graphSpecifier.Value.Substring(1); INode currGraph = new UriNode(null, currGraphUri); foreach (int id in result.SetIDs.ToList()) { ISet s = result[id]; if (s[gvar] == null) { // If Graph Variable is not yet bound for solution bind it s.Add(gvar, currGraph); } else if (!s[gvar].Equals(currGraph)) { // If Graph Variable is bound for solution and doesn't match // current Graph then we have to remove the solution result.Remove(id); } } } // Union solutions into the Results finalResult.Union(result); } // Reset the Active Graph after each pass context.Data.ResetActiveGraph(); datasetOk = false; } // Return the final result if (finalResult.IsEmpty) { finalResult = new NullMultiset(); } context.OutputMultiset = finalResult; } finally { if (datasetOk) { context.Data.ResetActiveGraph(); } } return(context.OutputMultiset); }
/// <summary> /// Gets the list of Search Results which match the given search term /// </summary> /// <param name="text">Search Term</param> /// <param name="callback">Callback to invoke when the operation completes</param> /// <param name="state">State to pass to the callback</param> public void Search(String text, PelletSearchServiceCallback callback, Object state) { String search = this._searchUri + "?search=" + Uri.EscapeDataString(text); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); request.Method = this.Endpoint.HttpMethods.First(); request.Accept = "text/json"; #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif String jsonText; JArray json; request.BeginGetResponse(result => { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result)) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd(); json = JArray.Parse(jsonText); response.Close(); //Parse the Response into Search Results List<SearchServiceResult> results = new List<SearchServiceResult>(); foreach (JToken res in json.Children()) { JToken hit = res.SelectToken("hit"); String type = (String)hit.SelectToken("type"); INode node; if (type.ToLower().Equals("uri")) { node = new UriNode(null, new Uri((String)hit.SelectToken("value"))); } else { node = new BlankNode(null, (String)hit.SelectToken("value")); } double score = (double)res.SelectToken("score"); results.Add(new SearchServiceResult(node, score)); } callback(results, state); } }, null); }