/// <summary> /// Gets a list of key value pairs listing Similar Individuals and their Similarity scores /// </summary> /// <param name="number">Number of Similar Individuals</param> /// <param name="individual">QName of a Individual to find Similar Individuals to</param> /// <returns></returns> public List<KeyValuePair<INode, double>> Similarity(int number, String individual) { IGraph g = this.SimilarityRaw(number, individual); List<KeyValuePair<INode, double>> similarities = new List<KeyValuePair<INode, double>>(); SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces = g.NamespaceMap; query.CommandText = "SELECT ?ind ?similarity WHERE { ?s cp:isSimilarTo ?ind ; cp:similarityValue ?similarity }"; try { Object results = g.ExecuteQuery(query); if (results is SparqlResultSet) { foreach (SparqlResult r in (SparqlResultSet)results) { if (r["similarity"].NodeType == NodeType.Literal) { similarities.Add(new KeyValuePair<INode, double>(r["ind"], Convert.ToDouble(((ILiteralNode)r["similarity"]).Value))); } } } else { throw new RdfReasoningException("Unable to extract the Similarity Information from the Similarity Graph returned by Pellet Server"); } } 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("Unable to extract the Similarity Information from the Similarity Graph returned by Pellet Server", ex); } return similarities; }
public BaseQuery(String query) { this._queryString = new SparqlParameterizedString(query); }
/// <summary> /// Internal method which generates the HTML Output for the Graph. /// </summary> /// <param name="context">Writer Context.</param> private void GenerateOutput(HtmlWriterContext context) { Object results; // Add the Namespaces we want to use later on context.QNameMapper.AddNamespace("owl", UriFactory.Create(NamespaceMapper.OWL)); context.QNameMapper.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF)); context.QNameMapper.AddNamespace("rdfs", UriFactory.Create(NamespaceMapper.RDFS)); context.QNameMapper.AddNamespace("dc", UriFactory.Create("http://purl.org/dc/elements/1.1/")); context.QNameMapper.AddNamespace("dct", UriFactory.Create("http://purl.org/dc/terms/")); context.QNameMapper.AddNamespace("vann", UriFactory.Create("http://purl.org/vocab/vann/")); context.QNameMapper.AddNamespace("vs", UriFactory.Create("http://www.w3.org/2003/06/sw-vocab-status/ns#")); // Find the Node that represents the Schema Ontology // Assumes there is exactly one thing given rdf:type owl:Ontology IUriNode ontology = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "Ontology")); IUriNode rdfType = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)); IUriNode rdfsLabel = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "label")); INode ontoNode = context.Graph.GetTriplesWithPredicateObject(rdfType, ontology).Select(t => t.Subject).FirstOrDefault(); INode ontoLabel = (ontoNode != null) ? context.Graph.GetTriplesWithSubjectPredicate(ontoNode, rdfsLabel).Select(t => t.Object).FirstOrDefault() : null; // Stuff for formatting // We'll use the Turtle Formatter to get nice QNames wherever possible context.NodeFormatter = new TurtleFormatter(context.QNameMapper); context.UriFormatter = (IUriFormatter)context.NodeFormatter; // Page Header context.HtmlWriter.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML+RDFa 1.0//EN\" \"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd\">"); context.HtmlWriter.WriteLine(); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Html); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Head); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Title); context.HtmlWriter.WriteEncodedText("Schema"); if (ontoNode != null && ontoLabel != null) { context.HtmlWriter.WriteEncodedText(" - " + ontoLabel.ToSafeString()); } else if (context.Graph.BaseUri != null) { context.HtmlWriter.WriteEncodedText(" - " + context.Graph.BaseUri.AbsoluteUri); } context.HtmlWriter.RenderEndTag(); if (!Stylesheet.Equals(String.Empty)) { context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, Stylesheet); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/css"); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet"); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Link); context.HtmlWriter.RenderEndTag(); } context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // Start Body context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Body); // Title context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H2); context.HtmlWriter.WriteEncodedText("Schema"); if (ontoNode != null && ontoLabel != null) { context.HtmlWriter.WriteEncodedText(" - " + ontoLabel.ToSafeString()); } else if (context.Graph.BaseUri != null) { context.HtmlWriter.WriteEncodedText(" - " + context.Graph.BaseUri.AbsoluteUri); } context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // Show the Description of the Schema (if any) if (ontoNode != null) { SparqlParameterizedString getOntoDescrip = new SparqlParameterizedString(); getOntoDescrip.Namespaces = context.QNameMapper; getOntoDescrip.CommandText = "SELECT * WHERE { @onto a owl:Ontology . OPTIONAL { @onto rdfs:comment ?description } . OPTIONAL { @onto vann:preferredNamespacePrefix ?nsPrefix ; vann:preferredNamespaceUri ?nsUri } . OPTIONAL { @onto dc:creator ?creator . ?creator (foaf:name | rdfs:label) ?creatorName } }"; getOntoDescrip.SetParameter("onto", ontoNode); try { results = context.Graph.ExecuteQuery(getOntoDescrip); if (results is SparqlResultSet) { if (!((SparqlResultSet)results).IsEmpty) { SparqlResult ontoInfo = ((SparqlResultSet)results)[0]; // Show rdfs:comment on the Ontology if (ontoInfo.HasValue("description")) { INode descrip = ontoInfo["description"]; if (descrip.NodeType == NodeType.Literal) { context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.Write(((ILiteralNode)descrip).Value); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); } } // Show Author Information if (ontoInfo.HasValue("creator")) { INode author = ontoInfo["creator"]; INode authorName = ontoInfo["creatorName"]; context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Em); context.HtmlWriter.WriteEncodedText("Schema created by "); if (author.NodeType == NodeType.Uri) { context.HtmlWriter.AddAttribute("href", ((IUriNode)author).Uri.AbsoluteUri); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); } switch (authorName.NodeType) { case NodeType.Uri: context.HtmlWriter.WriteEncodedText(((IUriNode)authorName).Uri.AbsoluteUri); break; case NodeType.Literal: context.HtmlWriter.WriteEncodedText(((ILiteralNode)authorName).Value); break; default: context.HtmlWriter.WriteEncodedText(authorName.ToString()); break; } if (author.NodeType == NodeType.Uri) { context.HtmlWriter.RenderEndTag(); } context.HtmlWriter.RenderEndTag(); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); } // Show the Namespace information for the Schema if (ontoInfo.HasValue("nsPrefix")) { if (ontoInfo["nsPrefix"].NodeType == NodeType.Literal && ontoInfo["nsUri"].NodeType == NodeType.Uri) { // Add this QName to the QName Mapper so we can get nice QNames later on String prefix = ((ILiteralNode)ontoInfo["nsPrefix"]).Value; context.QNameMapper.AddNamespace(prefix, ((IUriNode)ontoInfo["nsUri"]).Uri); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4); context.HtmlWriter.WriteEncodedText("Preferred Namespace Definition"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // Show human readable description of preferred Namespace Settings context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.WriteEncodedText("Preferred Namespace Prefix is "); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Strong); context.HtmlWriter.WriteEncodedText(prefix); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteEncodedText(" and preferred Namespace URI is "); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, context.QNameMapper.GetNamespaceUri(prefix).AbsoluteUri); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); context.HtmlWriter.WriteEncodedText(context.QNameMapper.GetNamespaceUri(prefix).AbsoluteUri); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.RenderEndTag(); // RDF/XML Syntax context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5); context.HtmlWriter.WriteEncodedText("RDF/XML Syntax"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%"); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre); int currIndent = context.HtmlWriter.Indent; context.HtmlWriter.Indent = 0; context.HtmlWriter.WriteEncodedText("<?xml version=\"1.0\" charset=\"utf-8\"?>"); context.HtmlWriter.WriteLine(); context.HtmlWriter.WriteEncodedText("<rdf:RDF xmlns:rdf=\"" + NamespaceMapper.RDF + "\" xmlns:" + prefix + "=\"" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + "\">"); context.HtmlWriter.WriteLine(); context.HtmlWriter.WriteEncodedText(" <!-- Your RDF here... -->"); context.HtmlWriter.WriteLine(); context.HtmlWriter.WriteEncodedText("</rdf:RDF>"); context.HtmlWriter.Indent = currIndent; context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // Turtle/N3 Syntax context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5); context.HtmlWriter.WriteEncodedText("Turtle/N3 Syntax"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%"); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre); currIndent = context.HtmlWriter.Indent; context.HtmlWriter.Indent = 0; context.HtmlWriter.WriteEncodedText("@prefix " + prefix + ": <" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + "> ."); context.HtmlWriter.Indent = currIndent; context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // SPARQL Syntax context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5); context.HtmlWriter.WriteEncodedText("SPARQL Syntax"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%"); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre); currIndent = context.HtmlWriter.Indent; context.HtmlWriter.Indent = 0; context.HtmlWriter.WriteEncodedText("PREFIX " + prefix + ": <" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + ">"); context.HtmlWriter.Indent = currIndent; context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); } } } } else { throw new RdfOutputException("Tried to make a SPARQL Query to determine Schema Information but an unexpected Query Result was returned"); } } catch (RdfQueryException queryEx) { throw new RdfOutputException("Tried to make a SPARQL Query to determine Schema Information but a Query Error occurred", queryEx); } } SparqlParameterizedString getPropertyRanges = new SparqlParameterizedString(); getPropertyRanges.Namespaces = new NamespaceMapper(); getPropertyRanges.Namespaces.AddNamespace("owl", UriFactory.Create(NamespaceMapper.OWL)); getPropertyRanges.CommandText = "SELECT ?range WHERE { { @property rdfs:range ?range . FILTER(ISURI(?range)) } UNION { @property rdfs:range ?union . ?union owl:unionOf ?ranges . { ?ranges rdf:first ?range } UNION { ?ranges rdf:rest+/rdf:first ?range } } }"; SparqlParameterizedString getPropertyDomains = new SparqlParameterizedString(); getPropertyDomains.Namespaces = getPropertyRanges.Namespaces; getPropertyDomains.CommandText = "SELECT ?domain WHERE { { @property rdfs:domain ?domain . FILTER(ISURI(?domain)) } UNION { @property rdfs:domain ?union . ?union owl:unionOf ?domains . { ?domains rdf:first ?domain } UNION { ?domains rdf:rest+/rdf:first ?domain } } }"; // Show lists of all Classes and Properties in the Schema context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4); context.HtmlWriter.WriteEncodedText("Class and Property Summary"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.WriteEncodedText("This Schema defines the following classes:"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); context.HtmlWriter.AddStyleAttribute("width", "90%"); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); // Get the Classes and Display SparqlParameterizedString getClasses = new SparqlParameterizedString(); getClasses.Namespaces = context.QNameMapper; getClasses.CommandText = "SELECT DISTINCT ?class WHERE { { ?class a rdfs:Class } UNION { ?class a owl:Class } FILTER(ISURI(?class)) } ORDER BY ?class"; try { results = context.Graph.ExecuteQuery(getClasses); if (results is SparqlResultSet) { SparqlResultSet rs = (SparqlResultSet)results; for (int i = 0; i < rs.Count; i++) { SparqlResult r = rs[i]; // Get the QName and output a Link to an anchor that we'll generate later to let // users jump to a Class/Property definition String qname = context.NodeFormatter.Format(r["class"]); context.HtmlWriter.AddAttribute("href", "#" + qname); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); context.HtmlWriter.WriteEncodedText(qname); context.HtmlWriter.RenderEndTag(); if (i < rs.Count - 1) { context.HtmlWriter.WriteEncodedText(" , "); } } } else { throw new RdfOutputException("Tried to make a SPARQL Query to find Classes in the Schema but an unexpected Query Result was returned"); } } catch (RdfQueryException queryEx) { throw new RdfOutputException("Tried to make a SPARQL Query to find Classes in the Schema but a Query Error occurred", queryEx); } context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.WriteEncodedText("This Schema defines the following properties:"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); context.HtmlWriter.AddStyleAttribute("width", "90%"); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); // Get the Properties and Display SparqlParameterizedString getProperties = new SparqlParameterizedString(); getProperties.Namespaces = context.QNameMapper; getProperties.CommandText = "SELECT DISTINCT ?property WHERE { { ?property a rdf:Property } UNION { ?property a owl:DatatypeProperty } UNION { ?property a owl:ObjectProperty } FILTER(ISURI(?property)) } ORDER BY ?property"; try { results = context.Graph.ExecuteQuery(getProperties); if (results is SparqlResultSet) { SparqlResultSet rs = (SparqlResultSet)results; for (int i = 0; i < rs.Count; i++) { SparqlResult r = rs[i]; // Get the QName and output a Link to an anchor that we'll generate later to let // users jump to a Class/Property definition String qname = context.NodeFormatter.Format(r["property"]); context.HtmlWriter.AddAttribute("href", "#" + qname); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); context.HtmlWriter.WriteEncodedText(qname); context.HtmlWriter.RenderEndTag(); if (i < rs.Count - 1) { context.HtmlWriter.WriteEncodedText(" , "); } } } else { throw new RdfOutputException("Tried to make a SPARQL Query to find Properties in the Schema but an unexpected Query Result was returned"); } } catch (RdfQueryException queryEx) { throw new RdfOutputException("Tried to make a SPARQL Query to find Properties in the Schema but a Query Error occurred", queryEx); } context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // Show details for each class context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H3); context.HtmlWriter.WriteEncodedText("Classes"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // Now create the URI Nodes we need for the next stage of Output IUriNode rdfsDomain = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "domain")); IUriNode rdfsRange = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "range")); IUriNode rdfsSubClassOf = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "subClassOf")); IUriNode rdfsSubPropertyOf = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "subPropertyOf")); IUriNode owlDisjointClass = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "disjointWith")); IUriNode owlEquivalentClass = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "equivalentClass")); IUriNode owlEquivalentProperty = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "equivalentProperty")); IUriNode owlInverseProperty = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "inverseOf")); // Alter our previous getClasses query to get additional details getClasses.CommandText = "SELECT ?class (SAMPLE(?label) AS ?classLabel) (SAMPLE(?description) AS ?classDescription) WHERE { { ?class a rdfs:Class } UNION { ?class a owl:Class } FILTER(ISURI(?class)) OPTIONAL { ?class rdfs:label ?label } OPTIONAL { ?class rdfs:comment ?description } } GROUP BY ?class ORDER BY ?class"; try { results = context.Graph.ExecuteQuery(getClasses); if (results is SparqlResultSet) { foreach (SparqlResult r in (SparqlResultSet)results) { if (!r.HasValue("class")) { continue; } String qname = context.NodeFormatter.Format(r["class"]); // Use a <div> for each Class context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Div); // Add the Anchor to which earlier Class summary links to context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Name, qname); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); context.HtmlWriter.RenderEndTag(); // Show Basic Class Information context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4); context.HtmlWriter.WriteEncodedText("Class: " + qname); context.HtmlWriter.RenderEndTag(); // Show "Local Name - Label" context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Em); if (TurtleSpecsHelper.IsValidQName(qname)) { context.HtmlWriter.WriteEncodedText(qname); } else { Uri temp = new Uri(qname, UriKind.RelativeOrAbsolute); if (!temp.Fragment.Equals(String.Empty)) { context.HtmlWriter.WriteEncodedText(temp.Fragment); } else { context.HtmlWriter.WriteEncodedText(temp.Segments.Last()); } } context.HtmlWriter.RenderEndTag(); if (r.HasValue("classLabel")) { if (r["classLabel"] != null && r["classLabel"].NodeType == NodeType.Literal) { context.HtmlWriter.WriteEncodedText(" - "); context.HtmlWriter.WriteEncodedText(((ILiteralNode)r["classLabel"]).Value); } } context.HtmlWriter.WriteLine(); context.HtmlWriter.WriteBreak(); context.HtmlWriter.WriteLine(); // Output further information about the class IEnumerable <Triple> ts; // Output any Subclasses ts = context.Graph.GetTriplesWithSubjectPredicate(rdfsSubClassOf, r["class"]); GenerateCaptionedInformation(context, "Has Sub Classes", ts, t => t.Object); // Output Properties which have this as domain/range ts = context.Graph.GetTriplesWithPredicateObject(rdfsDomain, r["class"]); GenerateCaptionedInformation(context, "Properties Include", ts, t => t.Subject); ts = context.Graph.GetTriplesWithPredicateObject(rdfsRange, r["class"]); GenerateCaptionedInformation(context, "Used With", ts, t => t.Subject); // Output any Equivalent Classes ts = context.Graph.GetTriplesWithSubjectPredicate(r["class"], owlEquivalentClass).Concat(context.Graph.GetTriplesWithPredicateObject(owlEquivalentClass, r["class"])); GenerateCaptionedInformation(context, "Equivalent Classes", ts, t => t.Subject.Equals(r["class"]) ? t.Object : t.Subject); // Output any Disjoint Classes ts = context.Graph.GetTriplesWithSubjectPredicate(r["class"], owlDisjointClass).Concat(context.Graph.GetTriplesWithPredicateObject(owlDisjointClass, r["class"])); GenerateCaptionedInformation(context, "Disjoint Classes", ts, t => t.Subject.Equals(r["class"]) ? t.Object : t.Subject); // Show the Class Description if (r.HasValue("classDescription")) { if (r["classDescription"] != null && r["classDescription"].NodeType == NodeType.Literal) { context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.Write(((ILiteralNode)r["classDescription"]).Value); context.HtmlWriter.RenderEndTag(); } } // End the </div> for the Class context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); } } else { throw new RdfOutputException("Tried to make a SPARQL Query to get Class Information from the Schema but an unexpected Query Result was returned"); } } catch (RdfQueryException queryEx) { throw new RdfOutputException("Tried to make a SPARQL Query to get Class Information from the Schema but a Query Error occurred", queryEx); } // Show details for each property context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H3); context.HtmlWriter.WriteEncodedText("Properties"); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); // Alter our previous getProperties query to get additional details getProperties.CommandText = "SELECT ?property (SAMPLE(?label) AS ?propertyLabel) (SAMPLE(?description) AS ?propertyDescription) WHERE { { ?property a rdf:Property } UNION { ?property a owl:ObjectProperty } UNION { ?property a owl:DatatypeProperty } FILTER(ISURI(?property)) OPTIONAL { ?property rdfs:label ?label } OPTIONAL { ?property rdfs:comment ?description } } GROUP BY ?property ORDER BY ?property"; try { results = context.Graph.ExecuteQuery(getProperties); if (results is SparqlResultSet) { foreach (SparqlResult r in (SparqlResultSet)results) { if (!r.HasValue("property")) { continue; } String qname = context.NodeFormatter.Format(r["property"]); // Use a <div> for each Property context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Div); // Add the Anchor to which earlier Property summary links to context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Name, qname); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); context.HtmlWriter.RenderEndTag(); // Show Basic Property Information context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4); context.HtmlWriter.WriteEncodedText("Property: " + qname); context.HtmlWriter.RenderEndTag(); // Show "Local Name - Label" context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Em); if (TurtleSpecsHelper.IsValidQName(qname)) { context.HtmlWriter.WriteEncodedText(qname); } else { Uri temp = new Uri(qname, UriKind.RelativeOrAbsolute); if (!temp.Fragment.Equals(String.Empty)) { context.HtmlWriter.WriteEncodedText(temp.Fragment); } else { context.HtmlWriter.WriteEncodedText(temp.Segments.Last()); } } context.HtmlWriter.RenderEndTag(); if (r.HasValue("propertyLabel")) { if (r["propertyLabel"] != null && r["propertyLabel"].NodeType == NodeType.Literal) { context.HtmlWriter.WriteEncodedText(" - "); context.HtmlWriter.WriteEncodedText(((ILiteralNode)r["propertyLabel"]).Value); } } context.HtmlWriter.WriteLine(); context.HtmlWriter.WriteBreak(); context.HtmlWriter.WriteLine(); // Output further information about the property IEnumerable <Triple> ts; // Output any Subproperties ts = context.Graph.GetTriplesWithSubjectPredicate(rdfsSubPropertyOf, r["property"]); GenerateCaptionedInformation(context, "Has Sub Properties", ts, t => t.Object); // Output Domain and Range // ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], rdfsDomain); // this.GenerateCaptionedInformation(context, "Has Domain", ts, t => t.Object); // ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], rdfsRange); // this.GenerateCaptionedInformation(context, "Has Range", ts, t => t.Object); getPropertyDomains.SetParameter("property", r["property"]); GenerateCaptionedInformation(context, "Has Domain", context.Graph.ExecuteQuery(getPropertyDomains) as SparqlResultSet, "domain"); getPropertyRanges.SetParameter("property", r["property"]); GenerateCaptionedInformation(context, "Has Range", context.Graph.ExecuteQuery(getPropertyRanges) as SparqlResultSet, "range"); // Output any Equivalent Properties ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], owlEquivalentProperty).Concat(context.Graph.GetTriplesWithPredicateObject(owlEquivalentProperty, r["property"])); GenerateCaptionedInformation(context, "Equivalent Properties", ts, t => t.Subject.Equals(r["property"]) ? t.Object : t.Subject); // Output any Disjoint Classes ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], owlInverseProperty).Concat(context.Graph.GetTriplesWithPredicateObject(owlInverseProperty, r["property"])); GenerateCaptionedInformation(context, "Inverse Property", ts, t => t.Subject.Equals(r["property"]) ? t.Object : t.Subject); // Show the Property Description if (r.HasValue("propertyDescription")) { if (r["propertyDescription"] != null && r["propertyDescription"].NodeType == NodeType.Literal) { context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.Write(((ILiteralNode)r["propertyDescription"]).Value); context.HtmlWriter.RenderEndTag(); } } // End the </div> for the Property context.HtmlWriter.RenderEndTag(); context.HtmlWriter.WriteLine(); } } else { throw new RdfOutputException("Tried to make a SPARQL Query to get Property Information from the Schema but an unexpected Query Result was returned"); } } catch (RdfQueryException queryEx) { throw new RdfOutputException("Tried to make a SPARQL Query to get Property Information from the Schema but a Query Error occurred", queryEx); } // End of Page context.HtmlWriter.RenderEndTag(); //End Body context.HtmlWriter.RenderEndTag(); //End Html }
/// <summary> /// Evaluates the Service Clause by generating instance(s) of <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> as required and issuing the query to the remote endpoint(s). /// </summary> /// <param name="context">Evaluation Context.</param> /// <returns></returns> public BaseMultiset Evaluate(SparqlEvaluationContext context) { bool bypassSilent = false; try { SparqlRemoteEndpoint endpoint; Uri endpointUri; String baseUri = (context.Query.BaseUri == null) ? String.Empty : context.Query.BaseUri.AbsoluteUri; SparqlParameterizedString sparqlQuery = new SparqlParameterizedString("SELECT * WHERE "); String pattern = _pattern.ToString(); pattern = pattern.Substring(pattern.IndexOf('{')); sparqlQuery.CommandText += pattern; // Pass through LIMIT and OFFSET to the remote service if (context.Query.Limit >= 0) { // Calculate a LIMIT which is the LIMIT plus the OFFSET // We'll apply OFFSET locally so don't pass that through explicitly int limit = context.Query.Limit; if (context.Query.Offset > 0) { limit += context.Query.Offset; } sparqlQuery.CommandText += " LIMIT " + limit; } // Select which service to use if (_endpointSpecifier.TokenType == Token.URI) { endpointUri = UriFactory.Create(Tools.ResolveUri(_endpointSpecifier.Value, baseUri)); endpoint = new SparqlRemoteEndpoint(endpointUri); } else if (_endpointSpecifier.TokenType == Token.VARIABLE) { // Get all the URIs that are bound to this Variable in the Input String var = _endpointSpecifier.Value.Substring(1); if (!context.InputMultiset.ContainsVariable(var)) { throw new RdfQueryException("Cannot evaluate a SERVICE clause which uses a Variable as the Service specifier when the Variable is unbound"); } List <IUriNode> services = new List <IUriNode>(); foreach (ISet s in context.InputMultiset.Sets) { if (s.ContainsVariable(var)) { if (s[var].NodeType == NodeType.Uri) { services.Add((IUriNode)s[var]); } } } services = services.Distinct().ToList(); // Now generate a Federated Remote Endpoint List <SparqlRemoteEndpoint> serviceEndpoints = new List <SparqlRemoteEndpoint>(); services.ForEach(u => serviceEndpoints.Add(new SparqlRemoteEndpoint(u.Uri))); endpoint = new FederatedSparqlRemoteEndpoint(serviceEndpoints); } else { // Note that we must bypass the SILENT operator in this case as this is not an evaluation failure // but a query syntax error bypassSilent = true; throw new RdfQueryException("SERVICE Specifier must be a URI/Variable Token but a " + _endpointSpecifier.GetType().ToString() + " Token was provided"); } // Where possible do substitution and execution to get accurate and correct SERVICE results context.OutputMultiset = new Multiset(); List <String> existingVars = (from v in _pattern.Variables where context.InputMultiset.ContainsVariable(v) select v).ToList(); if (existingVars.Any() || context.Query.Bindings != null) { // Pre-bound variables/BINDINGS clause so do substitution and execution // Build the set of possible bindings HashSet <ISet> bindings = new HashSet <ISet>(); if (context.Query.Bindings != null && !_pattern.Variables.IsDisjoint(context.Query.Bindings.Variables)) { // Possible Bindings comes from BINDINGS clause // In this case each possibility is a distinct binding tuple defined in the BINDINGS clause foreach (BindingTuple tuple in context.Query.Bindings.Tuples) { bindings.Add(new Set(tuple)); } } else { // Possible Bindings get built from current input (if there was a BINDINGS clause the variables it defines are not in this SERVICE clause) // In this case each possibility only contains Variables bound so far foreach (ISet s in context.InputMultiset.Sets) { Set t = new Set(); foreach (String var in existingVars) { t.Add(var, s[var]); } bindings.Add(t); } } // Execute the Query for every possible Binding and build up our Output Multiset from all the results foreach (ISet s in bindings) { // Q: Should we continue processing here if and when we hit an error? foreach (String var in s.Variables) { sparqlQuery.SetVariable(var, s[var]); } SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString()); context.CheckTimeout(); foreach (SparqlResult r in results) { Set t = new Set(r); foreach (String var in s.Variables) { t.Add(var, s[var]); } context.OutputMultiset.Add(t); } } return(context.OutputMultiset); } else { // No pre-bound variables/BINDINGS clause so just execute the query // Try and get a Result Set from the Service SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString()); // Transform this Result Set back into a Multiset foreach (SparqlResult r in results.Results) { context.OutputMultiset.Add(new Set(r)); } return(context.OutputMultiset); } } catch (Exception ex) { if (_silent && !bypassSilent) { // If Evaluation Errors are SILENT is specified then a Multiset containing a single set with all values unbound is returned // Unless some of the SPARQL queries did return results in which we just return the results we did obtain if (context.OutputMultiset.IsEmpty) { Set s = new Set(); foreach (String var in _pattern.Variables.Distinct()) { s.Add(var, null); } context.OutputMultiset.Add(s); } return(context.OutputMultiset); } else { throw new RdfQueryException("Query execution failed because evaluating a SERVICE clause failed - this may be due to an error with the remote service", ex); } } }
public static SparqlQuery ParseQuery(SparqlParameterizedString queryString) { return(ParseQuery(queryString.ToString(), new SparqlQueryParser())); }
public void DeleteHistoricResourceChain(Uri pidUri) { var deleteInboundLinksToAllHistoricResourcesQuery = @" WITH @historicGraph DELETE { ?resource ?predicate ?subject } WHERE { ?subject @hasPid @pidUri. ?subject @hasEntryLifeCycleStatus @historicLifecycleStatus. ?resource ?predicate ?subject }; "; var deleteMainDistributionEndpointsOfAllHistoricResourcesQuery = @" WITH @historicGraph DELETE { ?object ?predicate ?subObject } WHERE { ?subject @hasPid @pidUri. ?subject @hasEntryLifeCycleStatus @historicLifecycleStatus. ?subject @mainDistribution ?object. ?object ?predicate ?subObject }; "; var deleteDistributionEndpointsOfAllHistoricResourcesQuery = @" WITH @historicGraph DELETE { ?object ?predicate ?subObject } WHERE { ?subject @hasPid @pidUri. ?subject @hasEntryLifeCycleStatus @historicLifecycleStatus. ?subject @distribution ?object. ?object ?predicate ?subObject }; "; var deleteAllHistoricResourcesQuery = @" WITH @historicGraph DELETE { ?subject ?predicate ?object } WHERE { ?subject @hasPid @pidUri. ?subject @hasEntryLifeCycleStatus @historicLifecycleStatus. ?subject ?predicate ?object }; "; var deleteQuery = new SparqlParameterizedString { CommandText = deleteInboundLinksToLinkedResourceQuery + deleteOutboundLinksFromLinkedResourceQuery + deleteInboundLinksToAllHistoricResourcesQuery + deleteMainDistributionEndpointsOfAllHistoricResourcesQuery + deleteDistributionEndpointsOfAllHistoricResourcesQuery + deleteAllHistoricResourcesQuery }; deleteQuery.SetUri("historicGraph", new Uri(_metadataGraphConfigurationRepository.GetSingleGraph(InsertingGraph))); deleteQuery.SetPlainLiteral("queryGraphList", _metadataGraphConfigurationRepository.GetGraphs(QueryGraphs).JoinAsValuesList()); deleteQuery.SetUri("distribution", new Uri(Graph.Metadata.Constants.Resource.Distribution)); deleteQuery.SetUri("mainDistribution", new Uri(Graph.Metadata.Constants.Resource.MainDistribution)); deleteQuery.SetUri("hasEntryLifeCycleStatus", new Uri(Graph.Metadata.Constants.Resource.HasEntryLifecycleStatus)); deleteQuery.SetUri("historicLifecycleStatus", new Uri(Graph.Metadata.Constants.Resource.ColidEntryLifecycleStatus.Historic)); deleteQuery.SetUri("linkedResourceLifecycleStatus", new Uri(Graph.Metadata.Constants.Resource.ColidEntryLifecycleStatus.MarkedForDeletion)); deleteQuery.SetUri("hasPid", new Uri(Graph.Metadata.Constants.EnterpriseCore.PidUri)); deleteQuery.SetUri("pidUri", pidUri); _tripleStoreRepository.UpdateTripleStore(deleteQuery); }
/// <summary> /// Runs the task /// </summary> /// <returns></returns> protected override TaskResult RunTaskInternal() { if (this.Target.IsReadOnly) { throw new RdfStorageException("Cannot Copy/Move a Graph when the Target is a read-only Store!"); } switch (this.Name) { case "Rename": case "Move": //Move/Rename a Graph if (ReferenceEquals(this.Source, this.Target) && this.Source.StorageProvider is IUpdateableStorage) { //If the Source and Target are identical and it supports SPARQL Update natively then we'll just issue a MOVE command this.Information = "Issuing a MOVE command to rename Graph '" + this._sourceUri.ToSafeString() + "' to '" + this._targetUri.ToSafeString() + "'"; SparqlParameterizedString update = new SparqlParameterizedString { CommandText = "MOVE" }; if (this._sourceUri == null) { update.CommandText += " DEFAULT TO"; } else { update.CommandText += " GRAPH @source TO"; update.SetUri("source", this._sourceUri); } if (this._targetUri == null) { update.CommandText += " DEFAULT"; } else { update.CommandText += " GRAPH @target"; update.SetUri("target", this._targetUri); } ((IUpdateableStorage)this.Source.StorageProvider).Update(update.ToString()); this.Information = "MOVE command completed OK, Graph renamed to '" + this._targetUri.ToSafeString() + "'"; } else { //Otherwise do a load of the source graph writing through to the target graph IRdfHandler handler; IGraph g = null; if (this.Target.StorageProvider.UpdateSupported) { //If Target supports update then we'll use a WriteToStoreHandler combined with a GraphUriRewriteHandler handler = new WriteToStoreHandler(this.Target.StorageProvider, this._targetUri); handler = new GraphUriRewriteHandler(handler, this._targetUri); } else { //Otherwise we'll use a GraphHandler and do a save at the end g = new Graph(); handler = new GraphHandler(g); } handler = new CopyMoveProgressHandler(handler, this, "Moving", this.Target.StorageProvider.UpdateSupported); this._canceller = new CancellableHandler(handler); if (this.HasBeenCancelled) { this._canceller.Cancel(); } //Now start reading out the data this.Information = "Copying data from Graph '" + this._sourceUri.ToSafeString() + "' to '" + this._targetUri.ToSafeString() + "'"; this.Source.StorageProvider.LoadGraph(this._canceller, this._sourceUri); //If we weren't moving the data directly need to save the resulting graph now if (g != null) { this.Information = "Saving copied data to Target Store..."; this.Target.StorageProvider.SaveGraph(g); } //And finally since we've done a copy (not a move) so far we need to delete the original graph //to effect a rename if (this.Source.StorageProvider.DeleteSupported) { this.Information = "Removing source graph to complete the move operation"; this.Source.StorageProvider.DeleteGraph(this._sourceUri); this.Information = "Move completed OK, Graph moved to '" + this._targetUri.ToSafeString() + "'" + (ReferenceEquals(this.Source, this.Target) ? String.Empty : " on " + this.Target); } else { this.Information = "Copy completed OK, Graph copied to '" + this._targetUri.ToSafeString() + "'" + (ReferenceEquals(this.Source, this.Target) ? String.Empty : " on " + this.Target) + ". Please note that as the Source Triple Store does not support deleting Graphs so the Graph remains present in the Source Store"; } } break; case "Copy": if (ReferenceEquals(this.Source, this.Target) && this.Source.StorageProvider is IUpdateableStorage) { //If the Source and Target are identical and it supports SPARQL Update natively then we'll just issue a COPY command this.Information = "Issuing a COPY command to copy Graph '" + this._sourceUri.ToSafeString() + "' to '" + this._targetUri.ToSafeString() + "'"; SparqlParameterizedString update = new SparqlParameterizedString(); update.CommandText = "COPY"; if (this._sourceUri == null) { update.CommandText += " DEFAULT TO"; } else { update.CommandText += " GRAPH @source TO"; update.SetUri("source", this._sourceUri); } if (this._targetUri == null) { update.CommandText += " DEFAULT"; } else { update.CommandText += " GRAPH @target"; update.SetUri("target", this._targetUri); } ((IUpdateableStorage)this.Source.StorageProvider).Update(update.ToString()); this.Information = "COPY command completed OK, Graph copied to '" + this._targetUri.ToSafeString() + "'"; } else { //Otherwise do a load of the source graph writing through to the target graph IRdfHandler handler; IGraph g = null; if (this.Target.StorageProvider.UpdateSupported) { //If Target supports update then we'll use a WriteToStoreHandler combined with a GraphUriRewriteHandler handler = new WriteToStoreHandler(this.Target.StorageProvider, this._targetUri); handler = new GraphUriRewriteHandler(handler, this._targetUri); } else { //Otherwise we'll use a GraphHandler and do a save at the end g = new Graph(); handler = new GraphHandler(g); } handler = new CopyMoveProgressHandler(handler, this, "Copying", this.Target.StorageProvider.UpdateSupported); this._canceller = new CancellableHandler(handler); if (this.HasBeenCancelled) { this._canceller.Cancel(); } //Now start reading out the data this.Information = "Copying data from Graph '" + this._sourceUri.ToSafeString() + "' to '" + this._targetUri.ToSafeString() + "'"; this.Source.StorageProvider.LoadGraph(this._canceller, this._sourceUri); //If we weren't moving the data directly need to save the resulting graph now if (g != null) { this.Information = "Saving copied data to Store..."; this.Target.StorageProvider.SaveGraph(g); } this.Information = "Copy completed OK, Graph copied to '" + this._targetUri.ToSafeString() + "'" + (ReferenceEquals(this.Source, this.Target) ? String.Empty : " on " + this.Target.ToString()); } break; } return(new TaskResult(true)); }
/// <summary> /// Queries the Store using the Graph Pattern specified by the set of Statement Patterns /// </summary> /// <param name="graph">Graph Pattern</param> /// <param name="options">Query Options</param> /// <param name="sink">Results Sink</param> /// <remarks> /// <para> /// Implemented by converting the Statement Patterns into a SPARQL SELECT query and executing that against the underlying Store's SPARQL engine /// </para> /// <para> /// The only Query Option that is supported is the Limit option /// </para> /// </remarks> public void Query(Statement[] graph, SW.Query.QueryOptions options, SW.Query.QueryResultSink sink) { //Implement as a SPARQL SELECT SparqlParameterizedString queryString = new SparqlParameterizedString(); queryString.CommandText = "SELECT * WHERE {"; int p = 0; foreach (Statement stmt in graph) { //Add Subject queryString.CommandText += "\n"; if (stmt.Subject is Variable) { queryString.CommandText += stmt.Subject.ToString(); } else { queryString.CommandText += "@param" + p; queryString.SetParameter("param" + p, SemWebConverter.FromSemWeb(stmt.Subject, this._mapping)); p++; } queryString.CommandText += " "; //Add Predicate if (stmt.Predicate is Variable) { queryString.CommandText += stmt.Predicate.ToString(); } else { queryString.CommandText += "@param" + p; queryString.SetParameter("param" + p, SemWebConverter.FromSemWeb(stmt.Predicate, this._mapping)); p++; } queryString.CommandText += " "; //Add Object if (stmt.Object is Variable) { queryString.CommandText += stmt.Object.ToString(); } else { queryString.CommandText += "@param" + p; queryString.SetParameter("param" + p, SemWebConverter.FromSemWeb(stmt.Object, this._mapping)); p++; } queryString.CommandText += " ."; } queryString.CommandText += "}"; //Execute the Query and convert the Results Object results = this._store.ExecuteQuery(queryString.ToString()); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; sink.Init(rset.Variables.Select(v => new Variable(v)).ToArray()); if (rset.Count > 0) { int c = 0; foreach (SparqlResult r in rset) { //Apply Limit if applicable if (options.Limit > 0 && c >= options.Limit) { sink.Finished(); return; } //Convert the Set to VariableBindings for SemWeb Variable[] vars = r.Variables.Select(v => new Variable(v)).ToArray(); Resource[] resources = r.Variables.Select(v => SemWebConverter.ToSemWeb(r[v], this._mapping)).ToArray(); SW.Query.VariableBindings bindings = new SW.Query.VariableBindings(vars, resources); //Keep adding results until the sink tells us to stop if (!sink.Add(bindings)) { sink.Finished(); return; } c++; } sink.Finished(); } else { sink.Finished(); } } else { throw new RdfQueryException("Query returned an unexpected result where a SPARQL Result Set was expected"); } }
protected override VisitedPlaceDataObject DoGet(VisitedPlaceDataObject entity, LambdaExpression securityFilterExpression, List <string> includes, IObjectsDataSet context, Dictionary <string, object> parameters) { var userUri = DataProviderHelper.GetWebIdRootURL(entity.UserProfileUri); string visitedPlaceDocumentName = "myvisitedplaces.ttl"; string visitedPlacesDocumentUri = $"{userUri}/public/{visitedPlaceDocumentName}"; //string visitedPlaceUri = $"{visitedPlacesDocumentUri}#{entity.Id}"; // to be used with UriLoader.Load string tempfile = null; try { tempfile = DataProviderHelper.DownloadFile(visitedPlacesDocumentUri, ".ttl"); var g = new Graph(); g.LoadFromFile(tempfile); //UriLoader.Load(g, new Uri(visitedPlaceDocumentUri)); // NOT WORKING ... ??? SOMEHOW SHOULD WORK var query = new SparqlParameterizedString(); query.CommandText = @"SELECT * WHERE { @VisitedPlace <http://schema.org/startDate> ?Date ; <http://schema.org/description> ?Description. OPTIONAL { @VisitedPlace <http://generativeobjects.com/apps#VisitedPlaceType> ?PlaceOrCountry . } OPTIONAL { @VisitedPlace <http://dbpedia.org/ontology/Place> ?PlaceURI . } OPTIONAL { @VisitedPlace <http://dbpedia.org/class/yago/WikicatMemberStatesOfTheUnitedNations> ?CountryURI . } }"; // <http://dbpedia.org/class/yago/WikicatMemberStatesOfTheUnitedNations> ?CountryURI ; string visitedPlaceLocalFileUri = $"file://////{tempfile}#{entity.Id}"; query.SetUri("VisitedPlace", new Uri(visitedPlaceLocalFileUri)); var results = (SparqlResultSet)g.ExecuteQuery(query); var result = results.SingleOrDefault(); if (result == null) { throw new GOServerException("Cannot load the VisitedPlace"); } var visitedPlace = MapSparqlResultToVisitedPlace(result, mapId: false); visitedPlace.Id = entity.Id; visitedPlace.UserProfileUri = entity.UserProfileUri; var dataset = ApplicationSettings.Container.Resolve <IObjectsDataSet>(); dataset.AddObject(visitedPlace); return(visitedPlace); } finally { if (File.Exists(tempfile)) { File.Delete(tempfile); } } }
public void Commit() { // _logger.LogInformation("HERE COMES A SPARQL QUERY IN TRIPLESTORE_TRANSACTION" + _sparqlParameterized.ToString()); _commitable.Commit(_sparqlParameterized); _sparqlParameterized = new SparqlParameterizedString(); }
public TripleStoreTransaction(ICommitable commitable, ILogger <TripleStoreTransaction> logger) { _sparqlParameterized = new SparqlParameterizedString(); _commitable = commitable; _logger = logger; }
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> /// Generates an insert triple for each properties of the entity. For link types, triples are not sufficient, so a standalone query is built and returned as an additional query. /// </summary> /// <param name="entity">The entity for which the query is to be created</param> /// <param name="metadatas">Metadata fitting the entity type</param> /// <param name="namedGraph">The graph to which the additional queries refer.</param> /// <param name="additionalInsertString">All queries that must be executed separately from the triples.</param> /// <returns>List of triples belonging to one query and a separate string containing a number of queries.</returns> private IEnumerable <string> GenerateInsertTriples(Entity entity, IList <MetadataProperty> metadatas, Uri namedGraph, out string additionalInsertString) { additionalInsertString = string.Empty; var id = entity.Id; var propertyList = new List <string>(); foreach (var property in entity.Properties) { foreach (var prop in property.Value) { var predicate = property.Key; string propertyValue = string.Empty; Entity nestedObject = null; if (prop is DateTime) { propertyValue = prop.ToString("o"); } else { if (DynamicExtension.IsType <Entity>(prop, out Entity propEntity)) { propertyValue = propEntity.Id; nestedObject = propEntity; } else { propertyValue = prop.ToString(); } } // Properties that are null or empty do not have to be saved. if (string.IsNullOrWhiteSpace(propertyValue)) { continue; } var metadata = metadatas?.FirstOrDefault(m => m.Properties.GetValueOrNull(Metadata.Constants.EnterpriseCore.PidUri, true) == predicate); if (nestedObject != null) { var oldId = nestedObject.Id; nestedObject.Id = propertyValue; string nestedType = nestedObject.Properties.GetValueOrNull(Metadata.Constants.RDF.Type, true); // TODO: Remove all ?-operators var nestedMetadata = metadata?.NestedMetadata?.FirstOrDefault(m => m.Key == nestedType)?.Properties; // TODO: Concat or Addrange check propertyList = propertyList.Concat(GenerateInsertTriples(nestedObject, nestedMetadata, namedGraph, out var nestedAdditionalInsertString)).ToList(); if (!string.IsNullOrWhiteSpace(nestedAdditionalInsertString)) { additionalInsertString = additionalInsertString + nestedAdditionalInsertString; } // Set nestedObject to old id for deletion nestedObject.Id = oldId; } if (string.IsNullOrWhiteSpace(propertyValue)) { continue; } var parameterizedString = new SparqlParameterizedString(); if (LinkTypeMatches(metadata, predicate)) { if (namedGraph != null) { additionalInsertString += GenerateLinkTypeInsertQuery(id, predicate, propertyValue, namedGraph); } else { additionalInsertString += GenerateLinkTypeInsertQuery(id, predicate, propertyValue); } } else if (ReferenceEdgeMatches(predicate)) { parameterizedString.CommandText = $"<{id}> <{predicate}> @value"; parameterizedString.SetUri("value", new Uri(propertyValue)); propertyList.Add(parameterizedString.ToString()); } else if (NodekindIRIMatches(metadata, propertyValue)) { parameterizedString.CommandText = $"<{id}> <{predicate}> @value"; parameterizedString.SetUri("value", new Uri(propertyValue)); propertyList.Add(parameterizedString.ToString()); } else if (NodekindLiteralMatches(metadata, propertyValue)) { parameterizedString.CommandText = $"<{id}> <{predicate}> @value^^<{metadata.Properties[Metadata.Constants.Shacl.Datatype]}>"; parameterizedString.SetLiteral("value", propertyValue); propertyList.Add(parameterizedString.ToString()); } else { parameterizedString.CommandText = $"<{id}> <{predicate}> @value"; parameterizedString.SetLiteral("value", propertyValue); propertyList.Add(parameterizedString.ToString()); } } } return(propertyList); }
public static IEnumerable <NamespaceTerm> LoadNamespaceTerms(String namespaceUri) { //Don't load if already loaded if (_loadedNamespaces.Contains(namespaceUri)) { return(GetNamespaceTerms(namespaceUri)); } try { Graph g = new Graph(); try { UriLoader.Load(g, new Uri(namespaceUri)); if (g.Triples.Count == 0) { throw new Exception("Did not appear to receive an RDF Format from Namespace URI " + namespaceUri); } } catch { //Try and load from our local copy if there is one String prefix = GetDefaultPrefix(namespaceUri); if (!prefix.Equals(String.Empty)) { Stream localCopy = Assembly.GetExecutingAssembly().GetManifestResourceStream("VDS.RDF.Utilities.Editor.AutoComplete.Vocabularies." + prefix + ".ttl"); if (localCopy != null) { TurtleParser ttlparser = new TurtleParser(); ttlparser.Load(g, new StreamReader(localCopy)); } } } List <NamespaceTerm> terms = new List <NamespaceTerm>(); String termUri; //UriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); IUriNode rdfsClass = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "Class")); IUriNode rdfsLabel = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "label")); IUriNode rdfsComment = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "comment")); IUriNode rdfProperty = g.CreateUriNode(new Uri(NamespaceMapper.RDF + "Property")); IUriNode rdfsDatatype = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "Datatype")); SparqlParameterizedString queryString = new SparqlParameterizedString(); queryString.CommandText = "SELECT ?term (STR(?label) AS ?RawLabel) (STR(?comment) AS ?RawComment) WHERE { {{?term a @class} UNION {?term a @property} UNION {?term a @datatype}} OPTIONAL {?term @label ?label} OPTIONAL {?term @comment ?comment} }"; queryString.SetParameter("class", rdfsClass); queryString.SetParameter("property", rdfProperty); queryString.SetParameter("datatype", rdfsDatatype); queryString.SetParameter("label", rdfsLabel); queryString.SetParameter("comment", rdfsComment); Object results = g.ExecuteQuery(queryString.ToString()); if (results is SparqlResultSet) { foreach (SparqlResult r in ((SparqlResultSet)results)) { termUri = r["term"].ToString(); if (termUri.StartsWith(namespaceUri)) { //Use the Comment as the label if available if (r.HasValue("RawComment")) { if (r["RawComment"] != null) { terms.Add(new NamespaceTerm(namespaceUri, termUri.Substring(namespaceUri.Length), r["RawComment"].ToString())); continue; } } //Use the Label as the label if available if (r.HasValue("RawLabel")) { if (r["RawLabel"] != null) { terms.Add(new NamespaceTerm(namespaceUri, termUri.Substring(namespaceUri.Length), r["RawLabel"].ToString())); continue; } } //Otherwise no label terms.Add(new NamespaceTerm(namespaceUri, termUri.Substring(namespaceUri.Length))); } } } lock (_terms) { terms.RemoveAll(t => _terms.Contains(t)); _terms.AddRange(terms.Distinct()); } } catch (Exception ex) { //Ignore Exceptions - just means we won't have those namespace terms available } try { _loadedNamespaces.Add(namespaceUri); } catch (NullReferenceException) { //For some reason .Net sometimes throws a NullReferenceException here which we shall ignore } return(GetNamespaceTerms(namespaceUri)); }
public EntityTypeDto GetEntityTypes(string firstEntityType) { if (!firstEntityType.IsValidBaseUri()) { throw new InvalidFormatException(Constants.Messages.Identifier.IncorrectIdentifierFormat, firstEntityType); } SparqlParameterizedString queryString = new SparqlParameterizedString(); queryString.CommandText = @"SELECT DISTINCT * @fromMetadataNamedGraph @fromMetadataShacledNamedGraph @fromEnterpriseCoreOntologyNamedGraph WHERE { ?subject rdfs:subClassOf* @value . ?subject ?predicate ?object. BIND (exists { ?subClass rdfs:subClassOf ?subject } AS ?subClassExists ) FILTER(lang(str(?object)) IN (@language , """")) } ORDER BY ?subject"; queryString.SetPlainLiteral("fromMetadataNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasMetadataGraph).JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromMetadataShacledNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasShaclConstraintsGraph).JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromEnterpriseCoreOntologyNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasECOGraph).JoinAsFromNamedGraphs()); queryString.SetLiteral("language", Constants.I18n.DefaultLanguage); queryString.SetUri("value", new Uri(firstEntityType)); SparqlResultSet results = _tripleStoreRepository.QueryTripleStoreResultSet(queryString); if (results.IsEmpty) { return(null); } var entities = TransformQueryResults <EntityTypeDto>(results); var resourceTypeLookup = entities.ToDictionary(t => t.Id, t => t); foreach (var link in resourceTypeLookup) { var entity = link.Value; if (entity.Properties.TryGetValue(Constants.RDFS.SubClassOf, out var parents)) { foreach (var parentId in parents) { if (resourceTypeLookup.TryGetValue(parentId, out EntityTypeDto parent)) { parent.SubClasses.Add(entity); } } } } if (resourceTypeLookup.TryGetValue(firstEntityType, out var resourceTypeHierarchy)) { return(resourceTypeHierarchy); } ; return(null); }
protected override DataObjectCollection <VisitedPlaceDataObject> DoGetCollection(LambdaExpression securityFilterExpression, string filterPredicate, object[] filterArguments, string orderByPredicate, int pageNumber, int pageSize, List <string> includes, IObjectsDataSet context, Dictionary <string, object> parameters) { var userUri = GetUserBaseUriFromFilter(filterPredicate); if (userUri == null) { // search all the users registered in application var userNames = DataFacade.GOUserDataProvider.GetCollection(null).Select(u => u.UserName); var toReturn = new DataObjectCollection <VisitedPlaceDataObject>(); toReturn.ObjectsDataSet = ApplicationSettings.Container.Resolve <IObjectsDataSet>(); foreach (var userName in userNames) { try { var userfilter = $"UserProfileUri == \"{userName}\" && {filterPredicate}"; var subvisitedplaces = DoGetCollection(securityFilterExpression, userfilter, filterArguments, orderByPredicate, 0, 0, includes, context, parameters); foreach (var subvisitedplace in subvisitedplaces) { toReturn.Add(subvisitedplace); } } catch (Exception e) { } } return(toReturn); } string visitedPlaceDocumentName = "myvisitedplaces.ttl"; string visitedPlaceDocumentUri = $"{userUri}/public/{visitedPlaceDocumentName}"; string tempfile = null; var placeUriFilter = GetPropertyFromFilter(filterPredicate, "PlaceURI"); var countryUriFilter = GetPropertyFromFilter(filterPredicate, "CountryURI"); try { tempfile = DataProviderHelper.DownloadFile(visitedPlaceDocumentUri, ".ttl"); var g = new Graph(); g.LoadFromFile(tempfile); //UriLoader.Load(g, new Uri(visitedPlaceDocumentUri)); // NOT WORKING ... ??? SOMEHOW SHOULD WORK var query = new SparqlParameterizedString(); if (placeUriFilter == null && countryUriFilter == null) { query.CommandText = @"SELECT * WHERE { ?VisitedPlace a <http://generativeobjects.com/apps#VisitedPlace> ; <http://schema.org/startDate> ?Date; <http://schema.org/description> ?Description . OPTIONAL { ?VisitedPlace <http://generativeobjects.com/apps#VisitedPlaceType> ?PlaceOrCountry . } OPTIONAL { ?VisitedPlace <http://dbpedia.org/ontology/Place> ?PlaceURI . } OPTIONAL { ?VisitedPlace <http://dbpedia.org/class/yago/WikicatMemberStatesOfTheUnitedNations> ?CountryURI . } } "; ////<http://dbpedia.org/class/yago/WikicatMemberStatesOfTheUnitedNations> ?CountryURI ; if (pageNumber != 0 || pageSize != 0) { query.CommandText += $"LIMIT {pageSize} OFFSET {(pageNumber - 1) * pageSize}"; } } else if (placeUriFilter != null) { query.CommandText = @"SELECT * WHERE { ?VisitedPlace a <http://generativeobjects.com/apps#VisitedPlace> ; <http://dbpedia.org/ontology/Place> @PlaceUri ; <http://schema.org/startDate> ?Date; <http://schema.org/description> ?Description . OPTIONAL { ?VisitedPlace <http://generativeobjects.com/apps#VisitedPlaceType> ?PlaceOrCountry . } } "; query.SetUri("@PlaceUri", new Uri(placeUriFilter)); } else { query.CommandText = @"SELECT * WHERE { ?VisitedPlace a <http://generativeobjects.com/apps#VisitedPlace> ; <http://dbpedia.org/class/yago/WikicatMemberStatesOfTheUnitedNations> @CountryURI ; <http://schema.org/startDate> ?Date; <http://schema.org/description> ?Description . OPTIONAL { ?VisitedPlace <http://generativeobjects.com/apps#VisitedPlaceType> ?PlaceOrCountry . } } "; query.SetUri("@CountryURI", new Uri(countryUriFilter)); } var results = (SparqlResultSet)g.ExecuteQuery(query); var toReturn = new DataObjectCollection <VisitedPlaceDataObject>(); toReturn.ObjectsDataSet = ApplicationSettings.Container.Resolve <IObjectsDataSet>(); foreach (var result in results) { var visitedPlace = MapSparqlResultToVisitedPlace(result); visitedPlace.UserProfileUri = GetPropertyFromFilter(filterPredicate, "UserProfileUri"); toReturn.Add(visitedPlace); } return(toReturn); } finally { if (File.Exists(tempfile)) { File.Delete(tempfile); } } }
protected override int DoCount(LambdaExpression securityFilterExpression, string filterPredicate, object[] filterArguments, IObjectsDataSet context, Dictionary <string, object> parameters) { var userUri = GetUserBaseUriFromFilter(filterPredicate); if (userUri == null) { // search all the users registered in application var userNames = DataFacade.GOUserDataProvider.GetCollection(null).Select(u => u.UserName); int count = 0; foreach (var userName in userNames) { try { var userfilter = $"UserProfileUri == \"{userName}\" && {filterPredicate}"; count += DoCount(securityFilterExpression, userfilter, filterArguments, context, parameters); } catch (Exception e) { } } return(count); } string visitedPlaceDocumentName = "myvisitedplaces.ttl"; string visitedPlaceDocumentUri = $"{userUri}/public/{visitedPlaceDocumentName}"; string tempfile = null; var placeUriFilter = GetPropertyFromFilter(filterPredicate, "PlaceURI"); var countryUriFilter = GetPropertyFromFilter(filterPredicate, "CountryURI"); try { tempfile = DataProviderHelper.DownloadFile(visitedPlaceDocumentUri, ".ttl"); var g = new Graph(); g.LoadFromFile(tempfile); //UriLoader.Load(g, new Uri(visitedPlaceDocumentUri)); // NOT WORKING ... ??? SOMEHOW SHOULD WORK var query = new SparqlParameterizedString(); query.Namespaces.AddNamespace("go", new Uri("http://generativeobjects.com/apps#")); query.Namespaces.AddNamespace("schem", new Uri("http://schema.org")); if (placeUriFilter == null && countryUriFilter == null) { query.CommandText = @"SELECT count(?visitedplace) AS ?count WHERE { ?visitedplace a go:VisitedPlace } "; } else if (placeUriFilter != null) { query.CommandText = @"SELECT count(?visitedplace) AS ?count WHERE { ?visitedplace a go:VisitedPlace ; <http://dbpedia.org/ontology/Place> @PlaceUri . } "; query.SetUri("@PlaceUri", new Uri(placeUriFilter)); } else { query.CommandText = @"SELECT count(?visitedplace) AS ?count WHERE { ?visitedplace a go:VisitedPlace ; <http://dbpedia.org/class/yago/WikicatMemberStatesOfTheUnitedNations> @CountryURI . } "; query.SetUri("@CountryURI", new Uri(countryUriFilter)); } var results = (SparqlResultSet)g.ExecuteQuery(query); var res = results.Single(); var count = Convert.ToInt32((res.Single().Value as BaseLiteralNode).Value); return(count); } finally { if (File.Exists(tempfile)) { File.Delete(tempfile); } } }
static XElement CreateNuspecMetadata(TripleStore store, Uri packageUri) { SparqlParameterizedString sparql = new SparqlParameterizedString(); sparql.CommandText = Utils.GetResource("sparql.SelectPackageDetails.rq"); sparql.SetUri("package", packageUri); SparqlResult packageInfo = SparqlHelpers.Select(store, sparql.ToString()).FirstOrDefault(); if (packageInfo == null) { throw new ArgumentException(string.Format("no package details for {0}", packageUri)); } XElement metadata = new XElement(nuget.GetName("metadata")); metadata.Add(new XElement(nuget.GetName("id"), packageInfo["id"].ToString())); metadata.Add(new XElement(nuget.GetName("version"), packageInfo["version"].ToString())); // in the nuspec the published and owners fields are not present and ignored respectfully //if (packageInfo.HasBoundValue("published")) //{ // DateTime val = DateTime.Parse(((ILiteralNode)packageInfo["published"]).Value); // metadata.Add(new XElement(nuget.GetName("published"), val.ToUniversalTime().ToString("O"))); //} if (packageInfo.HasBoundValue("authors")) { metadata.Add(new XElement(nuget.GetName("authors"), packageInfo["authors"].ToString())); } if (packageInfo.HasBoundValue("description")) { metadata.Add(new XElement(nuget.GetName("description"), packageInfo["description"].ToString())); } if (packageInfo.HasBoundValue("summary")) { metadata.Add(new XElement(nuget.GetName("summary"), packageInfo["summary"].ToString())); } if (packageInfo.HasBoundValue("language")) { metadata.Add(new XElement(nuget.GetName("language"), packageInfo["language"].ToString())); } if (packageInfo.HasBoundValue("title")) { metadata.Add(new XElement(nuget.GetName("title"), packageInfo["title"].ToString())); } if (packageInfo.HasBoundValue("targetFramework")) { metadata.Add(new XElement(nuget.GetName("targetFramework"), packageInfo["targetFramework"].ToString())); } if (packageInfo.HasBoundValue("requireLicenseAcceptance")) { bool val = bool.Parse(((ILiteralNode)packageInfo["requireLicenseAcceptance"]).Value); metadata.Add(new XElement(nuget.GetName("requireLicenseAcceptance"), val)); } if (packageInfo.HasBoundValue("licenseUrl")) { metadata.Add(new XElement(nuget.GetName("licenseUrl"), packageInfo["licenseUrl"].ToString())); } if (packageInfo.HasBoundValue("iconUrl")) { metadata.Add(new XElement(nuget.GetName("iconUrl"), packageInfo["iconUrl"].ToString())); } if (packageInfo.HasBoundValue("projectUrl")) { metadata.Add(new XElement(nuget.GetName("projectUrl"), packageInfo["projectUrl"].ToString())); } if (packageInfo.HasBoundValue("releaseNotes")) { metadata.Add(new XElement(nuget.GetName("releaseNotes"), packageInfo["releaseNotes"].ToString())); } if (packageInfo.HasBoundValue("copyright")) { metadata.Add(new XElement(nuget.GetName("copyright"), packageInfo["copyright"].ToString())); } if (packageInfo.HasBoundValue("minClientVersion")) { metadata.Add(new XAttribute("minClientVersion", packageInfo["minClientVersion"].ToString())); } if (packageInfo.HasBoundValue("developmentDependency")) { bool val = bool.Parse(((ILiteralNode)packageInfo["developmentDependency"]).Value); metadata.Add(new XElement(nuget.GetName("developmentDependency"), val)); } return(metadata); }
/// <summary> /// Creates a new SPARQL View. /// </summary> /// <param name="sparqlQuery">SPARQL Query.</param> /// <param name="store">Triple Store to query.</param> public SparqlView(SparqlParameterizedString sparqlQuery, IInMemoryQueryableStore store) : this(sparqlQuery.ToString(), store) { }
public IActionResult Index(SearchViewModel model) { // Load ontology file IGraph g = new Graph(); var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "food-nt.owl"); FileLoader.Load(g, file); // Spartql query SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); query.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); query.Namespaces.AddNamespace("uni", new Uri("http://www.semanticweb.org/nnt/ontologies/2019/10/food-nt#")); string type = ""; string type_declare = ""; if (model.Type != 0) { type_declare = " ?food rdf:type ?type . "; } if (model.Type == 1) { type = " && ?type=uni:Ngu_coc "; } if (model.Type == 2) { type = " && ?type=uni:Khoai_cu "; } if (model.Type == 3) { type = " && ?type=uni:Hat_qua "; } query.CommandText = "SELECT ?food WHERE " + "{ ?food uni:hasEnergyPer100g ?en ." + " ?food uni:hasProteinPer100g ?pr ." + " ?food uni:hasFatPer100g ?fat ." + " ?food uni:hasCarbPer100g ?ca ." + type_declare + "FILTER(?en>=" + model.Energy + "&& ?pr>=" + model.Protein + "&& ?fat>=" + model.Fat + "&& ?ca>=" + model.Carb + type + ")}"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery queryEx = parser.ParseFromString(query); // Execute query Object result = g.ExecuteQuery(queryEx); string data = ""; if (result is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)result; INodeFormatter formatter = new TurtleFormatter(g); foreach (SparqlResult r in rset) { String d; INode n; if (r.TryGetValue("food", out n)) { switch (n.NodeType) { case NodeType.Uri: d = ((IUriNode)n).Uri.Fragment; break; case NodeType.Literal: d = ((ILiteralNode)n).Value; break; default: throw new RdfOutputException("Unexpected Node Type"); } } else { d = String.Empty; } data = data + d.Replace("#", "").Replace("_", " ") + "\n"; model.Result.Add(d.Replace("#", "").Replace("_", " ")); } } else { data += "NO RESULT!"; } return(PartialView("_Result", model.Result)); }
public static void AddCommonNamespaces(SparqlParameterizedString queryString) { queryString.Namespaces.AddNamespace("tt", UriFactory.Create("http://purl.org/rail/tt/")); queryString.Namespaces.AddNamespace("rdfs", UriFactory.Create("http://www.w3.org/2000/01/rdf-schema#")); }
public ActionResult Query(SearchQuery searchQuery) { searchQuery.ConceptSchemeList = GetSchemeList(); if (string.IsNullOrWhiteSpace(searchQuery.SearchText)) { ModelState.AddModelError(string.Empty, "search text is required"); return(View(searchQuery)); } string sparqlFilter = string.Empty; if (searchQuery.ExactMatch) { sparqlFilter = @"FILTER(LCASE(STR(?prefLabel)) = LCASE(@query))"; } string schemeBind = string.Empty; if (searchQuery.ConceptScheme != null && !searchQuery.ConceptScheme.Equals("-1")) { schemeBind = $"BIND(<{searchQuery.ConceptScheme}> as ?scheme)"; } var sparql = $@" PREFIX : <urn:> PREFIX luc: <http://www.ontotext.com/connectors/lucene#> PREFIX inst: <http://www.ontotext.com/connectors/lucene/instance#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> CONSTRUCT {{ :result :member ?entity . ?entity :score ?score ; :type skos:Concept ; :label ?label ; :collection ?collection ; :scheme ?scheme ; . ?collection :label ?collectionLabel . ?scheme :label ?schemeLabel . }} WHERE {{ {{ SELECT ?entity ?score WHERE {{ ?search a @connector ; luc:query @query ; luc:entities ?entity ; . ?entity luc:score ?score . }} }} {schemeBind} ?entity a skos:Concept ; skos:prefLabel ?prefLabel ; skos:inScheme ?scheme . ?scheme skos:prefLabel ?schemePrefLabel . OPTIONAL {{ ?collection skos:member ?entity ; skos:prefLabel ?collectionPrefLabel ; . BIND(STR(?collectionPrefLabel) AS ?collectionLabel) }} BIND(STR(?prefLabel) AS ?label) BIND(STR(?schemePrefLabel) AS ?schemeLabel) {sparqlFilter} }} "; var connector = new Uri(this.LuceneConnector); var pp = new SparqlParameterizedString(sparql); pp.SetUri("connector", connector); pp.SetLiteral("query", searchQuery.SearchText); searchQuery.Results = new DynamicGraph(this.VocabularyService.Execute(pp), subjectBaseUri: new Uri("urn:")); return(this.View(searchQuery)); }
public TripleStoreTransaction(ICommitable commitable) { _sparqlParameterized = new SparqlParameterizedString(); _commitable = commitable; }
public static void SetPlainLiteral(this SparqlParameterizedString sparqlParameterizedString, string name, string value) { sparqlParameterizedString.CommandText = sparqlParameterizedString.CommandText.Replace("@" + name, value, StringComparison.Ordinal); }
public void Commit() { _commitable.Commit(_sparqlParameterized); _sparqlParameterized = new SparqlParameterizedString(); }
/// <summary> /// Evaluates the Service Clause by generating instance(s) of <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> as required and issuing the query to the remote endpoint(s) /// </summary> /// <param name="context">Evaluation Context</param> /// <returns></returns> public BaseMultiset Evaluate(SparqlEvaluationContext context) { bool bypassSilent = false; try { #if SILVERLIGHT throw new PlatformNotSupportedException("SERVICE is not currently supported under Silverlight"); #else SparqlRemoteEndpoint endpoint; Uri endpointUri; String baseUri = (context.Query.BaseUri == null) ? String.Empty : context.Query.BaseUri.ToString(); SparqlParameterizedString sparqlQuery = new SparqlParameterizedString("SELECT * WHERE "); String pattern = this._pattern.ToString(); pattern = pattern.Substring(pattern.IndexOf('{')); sparqlQuery.CommandText += pattern; //Pass through LIMIT and OFFSET to the remote service if (context.Query.Limit >= 0) { //Calculate a LIMIT which is the LIMIT plus the OFFSET //We'll apply OFFSET locally so don't pass that through explicitly int limit = context.Query.Limit; if (context.Query.Offset > 0) limit += context.Query.Offset; sparqlQuery.CommandText += " LIMIT " + limit; } //Select which service to use if (this._endpointSpecifier.TokenType == Token.URI) { endpointUri = UriFactory.Create(Tools.ResolveUri(this._endpointSpecifier.Value, baseUri)); endpoint = new SparqlRemoteEndpoint(endpointUri); } else if (this._endpointSpecifier.TokenType == Token.VARIABLE) { //Get all the URIs that are bound to this Variable in the Input String var = this._endpointSpecifier.Value.Substring(1); if (!context.InputMultiset.ContainsVariable(var)) throw new RdfQueryException("Cannot evaluate a SERVICE clause which uses a Variable as the Service specifier when the Variable is unbound"); List<IUriNode> services = new List<IUriNode>(); foreach (ISet s in context.InputMultiset.Sets) { if (s.ContainsVariable(var)) { if (s[var].NodeType == NodeType.Uri) { services.Add((IUriNode)s[var]); } } } services = services.Distinct().ToList(); //Now generate a Federated Remote Endpoint List<SparqlRemoteEndpoint> serviceEndpoints = new List<SparqlRemoteEndpoint>(); services.ForEach(u => serviceEndpoints.Add(new SparqlRemoteEndpoint(u.Uri))); endpoint = new FederatedSparqlRemoteEndpoint(serviceEndpoints); } else { //Note that we must bypass the SILENT operator in this case as this is not an evaluation failure //but a query syntax error bypassSilent = true; throw new RdfQueryException("SERVICE Specifier must be a URI/Variable Token but a " + this._endpointSpecifier.GetType().ToString() + " Token was provided"); } //Where possible do substitution and execution to get accurate and correct SERVICE results context.OutputMultiset = new Multiset(); List<String> existingVars = (from v in this._pattern.Variables where context.InputMultiset.ContainsVariable(v) select v).ToList(); if (existingVars.Any() || context.Query.Bindings != null) { //Pre-bound variables/BINDINGS clause so do substitution and execution //Build the set of possible bindings HashSet<ISet> bindings = new HashSet<ISet>(); if (context.Query.Bindings != null && !this._pattern.Variables.IsDisjoint(context.Query.Bindings.Variables)) { //Possible Bindings comes from BINDINGS clause //In this case each possibility is a distinct binding tuple defined in the BINDINGS clause foreach (BindingTuple tuple in context.Query.Bindings.Tuples) { bindings.Add(new Set(tuple)); } } else { //Possible Bindings get built from current input (if there was a BINDINGS clause the variables it defines are not in this SERVICE clause) //In this case each possibility only contains Variables bound so far foreach (ISet s in context.InputMultiset.Sets) { Set t = new Set(); foreach (String var in existingVars) { t.Add(var, s[var]); } bindings.Add(t); } } //Execute the Query for every possible Binding and build up our Output Multiset from all the results foreach (ISet s in bindings) { //Q: Should we continue processing here if and when we hit an error? foreach (String var in s.Variables) { sparqlQuery.SetVariable(var, s[var]); } SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString()); context.CheckTimeout(); foreach (SparqlResult r in results) { Set t = new Set(r); foreach (String var in s.Variables) { t.Add(var, s[var]); } context.OutputMultiset.Add(t); } } return context.OutputMultiset; } else { //No pre-bound variables/BINDINGS clause so just execute the query //Try and get a Result Set from the Service SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString()); //Transform this Result Set back into a Multiset foreach (SparqlResult r in results.Results) { context.OutputMultiset.Add(new Set(r)); } return context.OutputMultiset; } #endif } catch (Exception ex) { if (this._silent && !bypassSilent) { //If Evaluation Errors are SILENT is specified then a Multiset containing a single set with all values unbound is returned //Unless some of the SPARQL queries did return results in which we just return the results we did obtain if (context.OutputMultiset.IsEmpty) { Set s = new Set(); foreach (String var in this._pattern.Variables.Distinct()) { s.Add(var, null); } context.OutputMultiset.Add(s); } return context.OutputMultiset; } else { throw new RdfQueryException("Query execution failed because evaluating a SERVICE clause failed - this may be due to an error with the remote service", ex); } } }
public void Dispose() { _sparqlParameterized = null; }
private void FillConnectionList(IGraph config, ListBox lbox) { SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS)); query.Namespaces.AddNamespace("dnr", new Uri(ConfigurationLoader.ConfigurationNamespace)); query.CommandText = "SELECT * WHERE { ?obj a @type . OPTIONAL { ?obj rdfs:label ?label } }"; query.CommandText += " ORDER BY DESC(?obj)"; query.SetParameter("type", config.CreateUriNode(UriFactory.Create(ConfigurationLoader.ClassStorageProvider))); SparqlResultSet results = config.ExecuteQuery(query) as SparqlResultSet; if (results != null) { foreach (SparqlResult r in results) { QuickConnect connect; if (r.HasValue("label") && r["label"] != null) { connect = new QuickConnect(config, r["obj"], r["label"].ToString()); } else { connect = new QuickConnect(config, r["obj"]); } lbox.Items.Add(connect); } } lbox.DoubleClick += new EventHandler((sender, args) => { QuickConnect connect = lbox.SelectedItem as QuickConnect; if (connect != null) { if (Properties.Settings.Default.AlwaysEdit) { IConnectionDefinition def = ConnectionDefinitionManager.GetDefinition(connect.Type); if (def != null) { def.PopulateFrom(connect.Graph, connect.ObjectNode); EditConnectionForm edit = new EditConnectionForm(def); if (edit.ShowDialog() == DialogResult.OK) { IStorageProvider manager = edit.Connection; StoreManagerForm storeManager = new StoreManagerForm(manager); storeManager.MdiParent = Program.MainForm; storeManager.Show(); //Add to Recent Connections Program.MainForm.AddRecentConnection(manager); this.Close(); } } else { MessageBox.Show("Selected Connection is not editable", "Connection Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { try { IStorageProvider manager = connect.GetConnection(); StoreManagerForm storeManager = new StoreManagerForm(manager); storeManager.MdiParent = Program.MainForm; storeManager.Show(); try { //Add to Recent Connections Program.MainForm.AddRecentConnection(manager); } catch { // silently ignore this error? seems like if MaxRecentConnections is hit, there is a bug in removing old connections... } this.Close(); } catch (Exception ex) { MessageBox.Show("Error Opening Connection " + connect.ToString() + ":\n" + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }); }
public IEnumerable <ColidEntryContactsCto> GetContactReferencedEntries(string userEmailAddress, IEnumerable <string> resourceTypes, IEnumerable <string> contactTypes) { if (!resourceTypes.Any()) { return(new List <ColidEntryContactsCto>()); } var parametrizedString = new SparqlParameterizedString { CommandText = @"SELECT DISTINCT * @fromResourceNamedGraph @fromEcoNamedGraph @fromMetadataNamedGraph @fromShacledNamedGraph WHERE { Values ?contactType { @contactTypes } ?predicate rdfs:range ?contactType. ?shacl sh:path ?predicate. OPTIONAL { ?shacl sh:group ?shaclGroup } ?shacl sh:name ?predicateLabel. { Select ?subject WHERE { Values ?type { @resourceTypes } ?subject a ?type. { ?subject ?predicate @userEmailAddress. } UNION { ?subject @distribution | @mainDistribution ?endpoint. ?endpoint ?predicate @userEmailAddress. } } } { ?subject ?predicate ?contact. } UNION { ?subject @distribution | @mainDistribution ?endpoint . ?endpoint ?predicate ?contact. } ?subject @hasPid ?pidUri. ?subject @hasLabel ?label. ?subject @hasConsumerGroup ?consumerGroup. FILTER NOT EXISTS { ?subject @hasPidEntryDraft ?draftResource } } ORDER BY ?subject " }; parametrizedString.SetPlainLiteral("fromResourceNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(MetadataGraphConfiguration.HasResourcesGraph).JoinAsFromNamedGraphs()); parametrizedString.SetPlainLiteral("fromEcoNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(MetadataGraphConfiguration.HasECOGraph).JoinAsFromNamedGraphs()); parametrizedString.SetPlainLiteral("fromMetadataNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(MetadataGraphConfiguration.HasMetadataGraph).JoinAsFromNamedGraphs()); parametrizedString.SetPlainLiteral("fromShacledNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(MetadataGraphConfiguration.HasShaclConstraintsGraph).JoinAsFromNamedGraphs()); parametrizedString.SetPlainLiteral("resourceTypes", resourceTypes.JoinAsValuesList()); parametrizedString.SetPlainLiteral("contactTypes", contactTypes.JoinAsValuesList()); parametrizedString.SetLiteral("userEmailAddress", userEmailAddress); parametrizedString.SetUri("hasLabel", new Uri(Resource.HasLabel)); parametrizedString.SetUri("hasPid", new Uri(EnterpriseCore.PidUri)); parametrizedString.SetUri("hasPidEntryDraft", new Uri(Resource.HasPidEntryDraft)); parametrizedString.SetUri("hasConsumerGroup", new Uri(Resource.HasConsumerGroup)); parametrizedString.SetUri("distribution", new Uri(Resource.Distribution)); parametrizedString.SetUri("mainDistribution", new Uri(Resource.MainDistribution)); var results = _tripleStoreRepository.QueryTripleStoreResultSet(parametrizedString); var groupedResults = results.GroupBy(res => res.GetNodeValuesFromSparqlResult("subject")?.Value); var contacts = groupedResults .Select(res => { var firstEntry = res.First(); var pidUriString = firstEntry.GetNodeValuesFromSparqlResult("pidUri")?.Value; var pidUri = string.IsNullOrWhiteSpace(pidUriString) ? null : new Uri(pidUriString); var consumerGroupString = firstEntry.GetNodeValuesFromSparqlResult("consumerGroup")?.Value; var consumerGroup = string.IsNullOrWhiteSpace(consumerGroupString) ? null : new Uri(consumerGroupString); var cep = new ColidEntryContactsCto() { Label = firstEntry.GetNodeValuesFromSparqlResult("label")?.Value, PidUri = pidUri, ConsumerGroup = consumerGroup, Contacts = res .Select(r => { var roleId = r.GetNodeValuesFromSparqlResult("predicate")?.Value; var contact = new ContactCto() { EmailAddress = r.GetNodeValuesFromSparqlResult("contact")?.Value, TypeUri = string.IsNullOrWhiteSpace(roleId) ? null : new Uri(roleId), TypeLabel = r.GetNodeValuesFromSparqlResult("predicateLabel")?.Value, IsTechnicalContact = IsTechnicalGroup(r.GetNodeValuesFromSparqlResult("shaclGroup")?.Value) }; return(contact); }) }; return(cep); }); return(contacts); }
/// <summary> /// Processes a PUT operation /// </summary> /// <param name="context">HTTP Context</param> public override void ProcessPut(HttpContext context) { //Get the payload assuming there is one IGraph g = this.ParsePayload(context); //Get the Graph URI of the Graph to be added Uri graphUri = this.ResolveGraphUri(context, g); //Determine whether the Graph already exists or not, if it doesn't then we have to send a 201 Response bool created = false; try { SparqlQueryParser parser = new SparqlQueryParser(); SparqlParameterizedString graphExistsQuery = new SparqlParameterizedString(); graphExistsQuery.CommandText = "ASK WHERE { GRAPH @graph { } }"; graphExistsQuery.SetUri("graph", graphUri); Object temp = this._queryProcessor.ProcessQuery(parser.ParseFromString(graphExistsQuery)); if (temp is SparqlResultSet) { created = !((SparqlResultSet)temp).Result; } } catch { //If any error occurs assume the Graph doesn't exist and so we'll return a 201 created created = true; } //Generate a set of commands based upon this StringBuilder cmdSequence = new StringBuilder(); if (graphUri != null) { cmdSequence.AppendLine("DROP SILENT GRAPH @graph ;"); cmdSequence.Append("CREATE SILENT GRAPH @graph"); } else { cmdSequence.Append("DROP SILENT DEFAULT"); } if (g != null) { cmdSequence.AppendLine(" ;"); if (graphUri != null) { cmdSequence.AppendLine("INSERT DATA { GRAPH @graph {"); } else { cmdSequence.AppendLine("INSERT DATA { "); } TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap); foreach (Triple t in g.Triples) { cmdSequence.AppendLine(t.ToString(formatter)); } if (graphUri != null) { cmdSequence.AppendLine("} }"); } else { cmdSequence.AppendLine("}"); } } SparqlParameterizedString put = new SparqlParameterizedString(cmdSequence.ToString()); put.Namespaces = g.NamespaceMap; if (graphUri != null) { put.SetUri("graph", graphUri); } SparqlUpdateCommandSet putCmds = this._parser.ParseFromString(put); this._updateProcessor.ProcessCommandSet(putCmds); this._updateProcessor.Flush(); //Return a 201 if required, otherwise the default behaviour of returning a 200 will occur automatically if (created) { context.Response.StatusCode = (int)HttpStatusCode.Created; } }
public static SparqlResultSet ExecuteQuery(SparqlParameterizedString expr) { return(ExecuteQuery(expr.ToString())); }
public IList <MetadataProperty> GetMetadataForEntityTypeInConfig(string entityType, string configIdentifier = null) { if (!entityType.IsValidBaseUri()) { throw new InvalidFormatException(Constants.Messages.Identifier.IncorrectIdentifierFormat, entityType); } MetadataGraphConfiguration usedConfig; if (string.IsNullOrWhiteSpace(configIdentifier)) { _logger.LogInformation($"Got request for entity type {entityType} with no config"); usedConfig = _metadataGraphConfigurationRepository.GetLatestConfiguration(); } else { _logger.LogInformation($"Got request for entity type {entityType} with config {configIdentifier}"); usedConfig = _metadataGraphConfigurationRepository.GetEntityById(configIdentifier); } SparqlParameterizedString queryString = new SparqlParameterizedString(); queryString.CommandText = @" SELECT * @fromMetadataNamedGraph @fromMetdataShaclNamedGraph @fromEnterpriseCoreOntologyNamedGraph @fromConsumerGroupNamedGraph WHERE { { @entityType rdfs:subClassOf* ?resourceType. @entityType rdfs:label ?typeLabel. FILTER(lang(?typeLabel) IN (@language , """")) Bind(@entityType as ?type). ?resourceType sh:property ?shaclConstraint. ?shaclConstraint ?shaclProperty ?shaclValue. OPTIONAL { ?shaclValue rdf:type ?dataType. } OPTIONAL { ?shaclConstraint @editWidget @nestedObjectEditor. ?shaclConstraint sh:class ?nested } OPTIONAL { ?shaclValue rdf:type sh:PropertyGroup. Bind(?shaclValue as ?group). ?shaclValue sh:order ?groupOrder. ?shaclValue rdfs:label ?grouplabel. ?shaclValue tosh:editGroupDescription ?editGroupDescription. ?shaclValue tosh:viewGroupDescription ?viewGroupDescription } OPTIONAL { ?shaclValue sh:class ?class. } } UNION { @entityType rdfs:subClassOf* ?resourceType. ?extraProperty rdfs:domain ?resourceType. ?extraProperty ?shaclProperty ?shaclValue } }"; queryString.SetPlainLiteral("fromMetadataNamedGraph", usedConfig.GetMetadataGraphs().JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromMetdataShaclNamedGraph", usedConfig.GetShaclGraphs().JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromEnterpriseCoreOntologyNamedGraph", usedConfig.GetEcoGraphs().JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromConsumerGroupNamedGraph", usedConfig.GetConsumerGroupGraphs().JoinAsFromNamedGraphs()); queryString.SetUri("entityType", new Uri(entityType)); queryString.SetLiteral("language", Constants.I18n.DefaultLanguage); queryString.SetUri("editWidget", new Uri(Constants.TopBraid.EditWidget)); queryString.SetUri("nestedObjectEditor", new Uri(Constants.TopBraid.NestedObjectEditor)); SparqlResultSet results = _tripleStoreRepository.QueryTripleStoreResultSet(queryString); var whereNotNullResults = results.Where(r => GetDataFromNode(r, "shaclConstraint")?.Value != null); var whereNullResults = results.Where(r => GetDataFromNode(r, "shaclConstraint").Value == null).ToList(); var groupedResults = whereNotNullResults.GroupBy(res => GetDataFromNode(res, "shaclConstraint")?.Value); var dict = GroupedSparqResultToDictionary(groupedResults); foreach (var r in whereNullResults) { var key = GetDataFromNode(r, "extraProperty")?.Value; if (dict.ContainsKey(key)) { dict[key].Add(r); } } var metaDataPropertyDictionary = dict.ToDictionary(r => r.Key, r => CreateMetadataPropertyFromList(r.Key, r.Value, configIdentifier)); // MainDistribution is a subproperty of distribution and gets no nested metadata if (metaDataPropertyDictionary.TryGetValue(Constants.Resource.MainDistribution, out var mainProperties) && metaDataPropertyDictionary.TryGetValue(Constants.Resource.Distribution, out var properties)) { mainProperties.NestedMetadata = properties.NestedMetadata; } var metaDataPropertyList = metaDataPropertyDictionary.Values.ToList(); // Remove all properties without label -> must have for property // metaDataPropertyList = metaDataPropertyList.Where(r => r.Properties.Any(t => t.Key == Shacl.Name)).ToList(); return(metaDataPropertyList); }
/// <summary> /// Gets a list of key value pairs listing Similar Individuals and their Similarity scores /// </summary> /// <param name="number">Number of Similar Individuals</param> /// <param name="individual">QName of a Individual to find Similar Individuals to</param> /// <param name="callback">Callback to invoke when the operation completes</param> /// <param name="state">State to pass to the callback</param> public void Similarity(int number, String individual, PelletSimilarityServiceCallback callback, Object state) { this.SimilarityRaw(number, individual, (g, _) => { List<KeyValuePair<INode, double>> similarities = new List<KeyValuePair<INode, double>>(); SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces = g.NamespaceMap; query.CommandText = "SELECT ?ind ?similarity WHERE { ?s cp:isSimilarTo ?ind ; cp:similarityValue ?similarity }"; Object results = g.ExecuteQuery(query); if (results is SparqlResultSet) { foreach (SparqlResult r in (SparqlResultSet)results) { if (r["similarity"].NodeType == NodeType.Literal) { similarities.Add(new KeyValuePair<INode, double>(r["ind"], Convert.ToDouble(((ILiteralNode)r["similarity"]).Value))); } } callback(similarities, state); } else { throw new RdfReasoningException("Unable to extract the Similarity Information from the Similarity Graph returned by Pellet Server"); } }, null); }