/// <summary> /// Creates a new Open Connection Form /// </summary> /// <param name="g">Graph contaning Connection Definitions</param> public OpenConnectionForm(IGraph g) { InitializeComponent(); //Find connections defined in the Configuration Graph this._g = g; INode genericManager = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.ClassGenericManager); INode rdfsLabel = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "label")); SparqlParameterizedString getConnections = new SparqlParameterizedString(); getConnections.QueryText = "SELECT ?obj ?label WHERE { ?obj a @type . OPTIONAL { ?obj @label ?label } } ORDER BY ?label"; getConnections.SetParameter("type", genericManager); getConnections.SetParameter("label", rdfsLabel); Object results = this._g.ExecuteQuery(getConnections.ToString()); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; foreach (SparqlResult r in rset) { this._connectionNodes.Add(r["obj"]); if (r.HasValue("label")) { this.lstConnections.Items.Add(r["label"]); } else { this.lstConnections.Items.Add(r["obj"]); } } } }
private Collection<BaprLocation> DbPedia_GetAllHospitalsNearby(double lat, double lng, IUserPreference userPreference) { string myQuery = "SELECT DISTINCT ?name ?website ?address ?phone ?lat ?long ?department ?opening_year ?health_care ?bed_count\n" + "WHERE { \n" + "?hospital a ?type. \n" + "?hospital ?p ?name. \n" + "Optional { ?hospital dbo:address ?address .}\n" + "Optional { ?hospital dbpproperty:website ?website. }\n" + "Optional { ?hospital foaf:phone ?phone. }\n" + "Optional { ?hospital schema:department ?department} \n" + "Optional { ?hospital dbo:openingYear ?opening_year} \n" + "Optional { ?hospital dbpproperty:healthcare ?health_care} \n" + "Optional { ?hospital dbo:bedCount ?bed_count} \n" + "?hospital geo:lat ?lat.\n" + "?hospital geo:long ?long.\n" + "FILTER (?p=<http://www.w3.org/2000/01/rdf-schema#label>).\n" + "FILTER (?type IN (<http://dbpedia.org/ontology/Hospital>, <http://schema.org/Hospital>)).\n" + "FILTER ( ?long > " + lng + " - 0.5 && ?long < " + lng + " + 0.5 && \n" + "?lat > " + lat + " - 0.5 && ?lat < " + lat + " + 0.5)\n" + "FILTER ( lang(?name) = 'en')}\n" + "LIMIT 30"; SparqlParameterizedString dbpediaQuery = new SparqlParameterizedString(); dbpediaQuery.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); dbpediaQuery.Namespaces.AddNamespace("dbpproperty", new Uri("http://dbpedia.org/property/")); dbpediaQuery.Namespaces.AddNamespace("dbo", new Uri("http://dbpedia.org/ontology/")); dbpediaQuery.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/spec/")); dbpediaQuery.Namespaces.AddNamespace("schema", new Uri("http://schema.org/")); dbpediaQuery.CommandText = myQuery; return BaprAPI.Utils.Utils.ParseSparqlQuery(dbpediaQuery, @"http://dbpedia.org/sparql"); }
public Collection<BaprLocation> DbPedia_GetShopsNearby(double lat, double lng, IUserPreference userPreference) { string myQuery = "SELECT DISTINCT ?name ?address ?opening_hours ?number_of_stores ?floors ?parking ?lat ?long \n" + "WHERE { \n" + "?shop a ?type. \n" + "?shop ?p ?name. \n" + "Optional { ?shop dbpproperty:address ?address. }" + "Optional { ?shop schema:openingHours ?opening_hours. }\n" + "Optional { ?shop dbpproperty:floors ?floors. }\n" + "Optional { ?shop dbpproperty:numberOfStores ?number_of_stores. }\n" + "Optional { ?shop dbpproperty:parking ?parking. }\n" + "?shop geo:lat ?lat.\n" + "?shop geo:long ?long.\n" + "FILTER (?p=<http://www.w3.org/2000/01/rdf-schema#label>).\n" + "FILTER (?type IN (<http://dbpedia.org/ontology/ShoppingMall>, <http://schema.org/ShoppingCenter>)).\n" + "FILTER ( ?long > " + lng + " - 0.5 && ?long < " + lng + " + 0.5 && \n" + "?lat > " + lat + " - 0.5 && ?lat < " + lat + " + 0.5)\n" + "FILTER ( lang(?name) = 'en')}\n" + "LIMIT 30"; SparqlParameterizedString dbpediaQuery = new SparqlParameterizedString(); dbpediaQuery.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); dbpediaQuery.Namespaces.AddNamespace("dbpproperty", new Uri("http://dbpedia.org/property/")); dbpediaQuery.Namespaces.AddNamespace("schema", new Uri("http://schema.org/")); dbpediaQuery.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); dbpediaQuery.CommandText = myQuery; return BaprAPI.Utils.Utils.ParseSparqlQuery(dbpediaQuery, @"http://dbpedia.org/sparql"); }
private Collection<BaprLocation> DbPedia_GetMuseumsNearby(double lat, double lng, IUserPreference userPreference) { string myQuery = "SELECT DISTINCT ?name ?website ?address ?phone ?lat ?long ?museum_type ?publictransit ?comment \n" + "WHERE { \n" + "?museum a ?type. \n" + "?museum ?p ?name. \n" + "Optional { ?museum dbpproperty:address ?address. }" + "Optional { ?museum dbpproperty:website ?website. }\n" + "Optional { ?museum foaf:phone ?phone. }" + "Optional { ?museum dbpproperty:type ?museum_type. }" + "Optional { ?museum dbpproperty:publictransit ?publictransit. }" + "Optional { ?s rdfs:comment ?comment. FILTER(langMatches(lang(?comment ), \"en\"))}\n" + "?museum geo:lat ?lat.\n" + "?museum geo:long ?long.\n" + "FILTER (?p=<http://www.w3.org/2000/01/rdf-schema#label>).\n" + "FILTER (?type IN (<http://dbpedia.org/ontology/Museum>, <http://schema.org/Museum>, <http://dbpedia.org/class/yago/Museum103800563>)).\n" + "FILTER ( ?long > " + lng + " - 0.5 && ?long < " + lng + " + 0.5 && \n" + "?lat > " + lat + " - 0.5 && ?lat < " + lat + " + 0.5)\n" + "FILTER ( lang(?name) = 'en')}\n" + "LIMIT 30"; SparqlParameterizedString dbpediaQuery = new SparqlParameterizedString(); dbpediaQuery.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); dbpediaQuery.Namespaces.AddNamespace("dbpedia-owl", new Uri("http://dbpedia.org/ontology/")); dbpediaQuery.Namespaces.AddNamespace("dbpproperty", new Uri("http://dbpedia.org/property/")); dbpediaQuery.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/spec/")); dbpediaQuery.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); dbpediaQuery.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); dbpediaQuery.CommandText = myQuery; return BaprAPI.Utils.Utils.ParseSparqlQuery(dbpediaQuery, @"http://dbpedia.org/sparql"); }
private Collection<BaprLocation> LinkedGeoData_GetMuseumsNearby(double lat, double lng, IUserPreference userPreference) { string myQuery = "SELECT DISTINCT ?name ?address ?homepage ?lat ?long ?opening_hours \n" + "WHERE { \n" + "?museum a ?type. \n" + "?museum ?p ?name. \n" + "Optional { ?museum lgdo:address ?address. }\n" + "Optional { ?museum foaf:homepage ?homepage. }\n" + "Optional { ?museum foaf:phone ?phone. }\n" + "Optional { ?museum lgdo:opening_hours ?opening_hours .}\n " + "?museum geo:lat ?lat.\n" + "?museum geo:long ?long.\n" + "FILTER (?p=<http://www.w3.org/2000/01/rdf-schema#label>).\n" + "FILTER (?type IN (<http://linkedgeodata.org/ontology/Museum>, <http://schema.org/Museum>)).\n" + "FILTER ( ?long > " + lng + " - 0.5 && ?long < " + lng + " + 0.5 && \n" + "?lat > " + lat + " - 0.5 && ?lat < " + lat + " + 0.5)}\n" + "LIMIT 30"; SparqlParameterizedString dbpediaQuery = new SparqlParameterizedString(); dbpediaQuery.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); dbpediaQuery.Namespaces.AddNamespace("lgdo", new Uri("http://linkedgeodata.org/ontology/")); dbpediaQuery.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/spec/")); dbpediaQuery.CommandText = myQuery; return BaprAPI.Utils.Utils.ParseSparqlQuery(dbpediaQuery, @"http://linkedgeodata.org/sparql"); }
public Collection<BaprLocation> DBpedia_GetRestaurantsNearby(double lat, double lng, IUserPreference userPreference) { var cuisine = BaprAPI.Utils.Utils.GetCuisines(userPreference, true); string queryRestaurantsDBpedia = "SELECT DISTINCT ?name ?lat ?long ?cuisine ?comment ?website ?address ?dress_code ?head_chef ?reservations \n" + " WHERE { \n" + "?f rdf:type dbo:Restaurant .\n" + "?f rdfs:label ?name .\n" + "?f geo:lat ?lat .\n" + "?f geo:long ?long .\n" + "Optional { ?f dbo:cuisine ?cuisine .}\n " + "Optional { ?f rdfs:comment ?comment . FILTER(langMatches(lang(?comment ), \"en\"))}\n " + "Optional { ?f foaf:homepage ?website .}\n " + "Optional { ?f dbo:address ?address .}\n" + "Optional { ?f dbp:dressCode ?dress_code .} \n" + "Optional { ?f dbp:headChef ?head_chef .} \n" + "Optional { ?f dbp:reservations ?reservations .} \n" + " FILTER ( langMatches(lang(?name), \"EN\")\n" + " && ?lat > " + lat + " - 0.5 && ?lat < " + lat + " + 0.5\n" + " && ?long > " + lng + " - 0.5 && ?long < " + lng + " + 0.5\n" + (!string.IsNullOrEmpty(cuisine) ? " && lcase(?cuisine) in (" + cuisine + ") " : string.Empty) + ")}\n" +"LIMIT 30"; //Create a Parameterized String SparqlParameterizedString queryString = new SparqlParameterizedString(); //Add a namespace declaration queryString.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); queryString.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); queryString.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); queryString.Namespaces.AddNamespace("dbo", new Uri("http://dbpedia.org/ontology/")); queryString.Namespaces.AddNamespace("dbp", new Uri("http://dbpedia.org/property/")); queryString.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); queryString.CommandText = queryRestaurantsDBpedia; return BaprAPI.Utils.Utils.ParseSparqlQuery(queryString, @"http://dbpedia.org/sparql"); }
private Collection<BaprLocation> GetFromDbpedia(double latitude, double longitude, IUserPreference userPreference) { string searchHotelsQuery = "SELECT DISTINCT ?lat ?long ?name ?website ?address ?number_of_restaurants " + "?star_rating ?number_of_rooms ?number_of_suites ?comment ?arhitect ?chain " + " WHERE {\n ?s a dbo:Hotel ." + "?s rdfs:label ?name .\n" + "?s geo:lat ?lat .\n" + "?s geo:long ?long .\n" + "OPTIONAL { ?s rdfs:comment ?comment. FILTER(langMatches(lang(?comment ), \"en\"))}\n" + "OPTIONAL { ?s dbo:arhitect ?arhitect. }\n" + "OPTIONAL { ?s dbp:chain ?chain. }\n" + "OPTIONAL { ?s foaf:homepage ?website .}\n" + "OPTIONAL { ?s dbo:address ?address .}\n" + "OPTIONAL { ?s dbp:numberOfRestaurants ?number_of_restaurants.} \n" + "OPTIONAL { ?s dbp:starRating ?star_rating. } \n" + "OPTIONAL { ?s dbp:numberOfRooms ?number_of_rooms. } \n" + "OPTIONAL { ?s dbp:numberOfSuites ?number_of_suites. } \n" + "FILTER ( langMatches(lang(?name), \"EN\")" + " && ?lat > " + latitude + " - 0.5 && ?lat < " + latitude + " + 0.5" + " && ?long > " + longitude + " - 0.5 && ?long < " + longitude + " + 0.5 )\n" + " } LIMIT 10"; SparqlParameterizedString sparqlQueryString = new SparqlParameterizedString(); sparqlQueryString.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); sparqlQueryString.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); sparqlQueryString.Namespaces.AddNamespace("dbo", new Uri("http://dbpedia.org/ontology/")); sparqlQueryString.Namespaces.AddNamespace("dbp", new Uri("http://dbpedia.org/property/")); sparqlQueryString.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); sparqlQueryString.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); sparqlQueryString.CommandText = searchHotelsQuery; return BaprAPI.Utils.Utils.ParseSparqlQuery(sparqlQueryString, @"http://dbpedia.org/sparql"); }
public void SparqlNegationMinusComplex2() { SparqlParameterizedString negQuery = new SparqlParameterizedString(); negQuery.Namespaces.AddNamespace("ex", new Uri("http://example.org/vehicles/")); negQuery.CommandText = "SELECT ?s WHERE { ?s a ex:Car MINUS { ?s ex:Speed ?speed FILTER(NOT EXISTS { ?s ex:PassengerCapacity ?passengers }) } }"; SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces = negQuery.Namespaces; query.CommandText = "SELECT ?s WHERE { ?s a ex:Car OPTIONAL { ?s ex:Speed ?speed OPTIONAL { ?s ex:PassengerCapacity ?passengers} FILTER(!BOUND(?passengers)) } FILTER(!BOUND(?speed)) }"; this.TestNegation(this.GetTestData(), negQuery, query); }
public void SparqlBindingsSimple() { SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces.AddNamespace("ex", new Uri("http://example.org/vehicles/")); query.CommandText = "SELECT ?subj WHERE { ?subj a ex:Car }"; SparqlParameterizedString bindingsQuery = new SparqlParameterizedString(); bindingsQuery.Namespaces = query.Namespaces; bindingsQuery.CommandText = "SELECT ?subj WHERE { ?subj a ?type } BINDINGS ?type { ( ex:Car ) }"; this.TestBindings(this.GetTestData(), bindingsQuery, query); }
public void SparqlParameterizedStringWithNulls2() { SparqlParameterizedString query = new SparqlParameterizedString(); query.CommandText = "SELECT * WHERE { @s ?p ?o }"; //Set a URI to a valid value query.SetUri("s", new Uri("http://example.org")); Console.WriteLine(query.ToString()); Console.WriteLine(); //Set the URI to a null query.SetUri("s", null); }
private IEnumerable<SparqlUpdateCommand> GetDeleteEntityCommands(IEnumerable<EntityId> entityGraphs) { foreach (EntityId entityId in entityGraphs) { SparqlParameterizedString delete = new SparqlParameterizedString(DeleteEntityGraphCommandText); delete.SetUri("metaGraph", _metaGraphUri); delete.SetUri("entityId", entityId.Uri); foreach (var command in _parser.ParseFromString(delete).Commands) { yield return command; } } }
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 " + ConfigurationLoader.ClassGenericManager + " . OPTIONAL { ?obj rdfs:label ?label } }"; query.CommandText += " ORDER BY DESC(?obj)"; 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) { try { IGenericIOManager manager = connect.GetConnection(); StoreManagerForm storeManager = new StoreManagerForm(manager); storeManager.MdiParent = Program.MainForm; storeManager.Show(); //Add to Recent Connections Program.MainForm.AddRecentConnection(manager); this.Close(); } catch (Exception ex) { MessageBox.Show("Error Opening Connection " + connect.ToString() + ":\n" + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }); }
protected override async Task ProcessStore(TripleStore store) { ResolverCollectorEventSource.Log.ProcessingBatch(BatchCount); try { SparqlResultSet distinctIds = SparqlHelpers.Select(store, Utils.GetResource("sparql.SelectDistinctPackage.rq")); IDictionary<Uri, IGraph> resolverResources = new Dictionary<Uri, IGraph>(); foreach (SparqlResult row in distinctIds) { string id = row["id"].ToString(); SparqlParameterizedString sparql = new SparqlParameterizedString(); sparql.CommandText = Utils.GetResource("sparql.ConstructResolverGraph.rq"); string baseAddress = _storage.BaseAddress.ToString(); sparql.SetLiteral("id", id); sparql.SetLiteral("base", baseAddress); sparql.SetLiteral("extension", ".json"); sparql.SetLiteral("galleryBase", GalleryBaseAddress); sparql.SetLiteral("contentBase", ContentBaseAddress); IGraph packageRegistration = SparqlHelpers.Construct(store, sparql.ToString()); if (packageRegistration.Triples.Count == 0) { throw new Exception("packageRegistration.Triples.Count == 0"); } Uri registrationUri = new Uri(baseAddress + id.ToLowerInvariant() + ".json"); resolverResources.Add(registrationUri, packageRegistration); } if (resolverResources.Count != distinctIds.Count) { throw new Exception("resolverResources.Count != distinctIds.Count"); } await MergeAll(resolverResources); } finally { ResolverCollectorEventSource.Log.ProcessedBatch(BatchCount); store.Dispose(); } }
private IEnumerable<SparqlUpdateCommand> GetDeleteDataCommands(IEnumerable<RomanticWeb.Model.EntityQuad> quads) { foreach (var quad in quads) { SparqlParameterizedString insert = new SparqlParameterizedString(DeleteDataCommandText); insert.SetParameter("subject", quad.Subject.UnWrapNode(_nodeFactory)); insert.SetParameter("predicate", quad.Predicate.UnWrapNode(_nodeFactory)); insert.SetParameter("object", quad.Object.UnWrapNode(_nodeFactory)); insert.SetUri("graph", quad.Graph.UnWrapGraphUri()); foreach (var command in _parser.ParseFromString(insert).Commands) { yield return command; } } }
/// <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; }
/// <summary> /// Ensures that a specific Object Factory type is registered in a Configuration Graph /// </summary> /// <param name="context">Configuration Serialization Context</param> /// <param name="factoryType">Factory Type</param> internal static void EnsureObjectFactory(this ConfigurationSerializationContext context, Type factoryType) { INode dnrType = ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.PropertyType); INode rdfType = context.Graph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); String assm = Assembly.GetAssembly(factoryType).FullName;//Assembly.GetCallingAssembly().FullName; if (assm.Contains(',')) assm = assm.Substring(0, assm.IndexOf(',')); //Firstly need to ensure our object factory has been referenced SparqlParameterizedString factoryCheck = new SparqlParameterizedString(); factoryCheck.Namespaces.AddNamespace("dnr", new Uri(ConfigurationLoader.ConfigurationNamespace)); factoryCheck.CommandText = "ASK WHERE { ?factory a dnr:ObjectFactory ; dnr:type '" + factoryType.FullName + ", " + assm + "' . }"; SparqlResultSet rset = context.Graph.ExecuteQuery(factoryCheck) as SparqlResultSet; if (!rset.Result) { INode factory = context.Graph.CreateBlankNode(); context.Graph.Assert(new Triple(factory, rdfType, ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.ClassObjectFactory))); context.Graph.Assert(new Triple(factory, dnrType, context.Graph.CreateLiteralNode(factoryType.FullName + ", " + assm))); } }
async Task ProcessStore(TripleStore store) { try { SparqlResultSet distinctIds = SparqlHelpers.Select(store, Utils.GetResource("sparql.SelectDistinctPackage.rq")); IDictionary<Uri, IGraph> resolverResources = new Dictionary<Uri, IGraph>(); foreach (SparqlResult row in distinctIds) { string id = row["id"].ToString(); SparqlParameterizedString sparql = new SparqlParameterizedString(); sparql.CommandText = Utils.GetResource("sparql.ConstructResolverGraph.rq"); string baseAddress = _storage.BaseAddress + _storage.Container + "/resolver/"; sparql.SetLiteral("id", id); sparql.SetLiteral("base", baseAddress); sparql.SetLiteral("extension", ".json"); IGraph packageRegistration = SparqlHelpers.Construct(store, sparql.ToString()); Uri registrationUri = new Uri(baseAddress + id.ToLowerInvariant() + ".json"); resolverResources.Add(registrationUri, packageRegistration); } if (resolverResources.Count != distinctIds.Count) { throw new Exception("resolverResources.Count != distinctIds.Count"); } await MergeAll(resolverResources); } finally { store.Dispose(); } }
public ICollection<BaprLocation> GetFromDbpedia(string text, double latitude, double longitude, IUserPreference userPreference) { var cuisineFromDb = BaprAPI.Utils.Utils.GetCuisines(userPreference, true); var interests = BaprAPI.Utils.Utils.GetInterests(userPreference); string searchQueryByText = "SELECT DISTINCT ?lat ?long ?name ?address ?cuisine ?website ?established ?comment WHERE{\n" + "?s a dbo:Location .\n" + "?s geo:lat ?lat .\n" + "?s geo:long ?long .\n" + "?s rdfs:label ?name.\n" + "?s a ?type. \n" + "OPTIONAL { ?s dbp:established ?established.}\n" + "OPTIONAL { ?s rdfs:comment ?comment. FILTER(langMatches(lang(?comment ), \"en\"))}\n" + "OPTIONAL { ?s dbo:address ?address .}\n " + "OPTIONAL { ?s dbo:cuisine ?cuisine .}\n" + "OPTIONAL { ?s foaf:homepage ?website .}\n" + "FILTER(langMatches(lang(?name ), \"en\") " + " && ?lat >" + latitude + " - 0.5 && ?lat < " + latitude + "+ 0.5 " + " && ?long > " + longitude + " - 0.5 && ?long < " + longitude + " + 0.5" + " && contains(lcase(?name),lcase(\"" + text.ToLower() + "\"))" + " && ((?type=dbo:Restaurant " + (!string.IsNullOrEmpty(cuisineFromDb) ? "&& lcase(?cuisine) in (" + cuisineFromDb + ")" : string.Empty) + ")\n" + "|| (?type = dbo:Museum " + (!string.IsNullOrEmpty(interests) ? " &&?type in (" + interests + ")" : string.Empty) + ")\n" + "|| ?type=dbo:Town || ?type=dbo:Village " + "|| ?type=dbo:Park || ?type=dbo:Garden || ?type=dbo:HistoricPlace || ?type=dbo:Monument)) " + "}LIMIT 10"; SparqlParameterizedString sparqlQueryString = new SparqlParameterizedString(); sparqlQueryString.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); sparqlQueryString.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); sparqlQueryString.Namespaces.AddNamespace("dbo", new Uri("http://dbpedia.org/ontology/")); sparqlQueryString.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); sparqlQueryString.Namespaces.AddNamespace("dbp", new Uri("http://dbpedia.org/property/")); sparqlQueryString.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); sparqlQueryString.CommandText = searchQueryByText; return BaprAPI.Utils.Utils.ParseSparqlQuery(sparqlQueryString, @"http://dbpedia.org/sparql"); }
public void SparqlFilterOptionalNotBound() { Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces.AddNamespace("rdf", new Uri(NamespaceMapper.RDF)); query.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS)); query.CommandText = "SELECT * WHERE { ?property a rdf:Property . OPTIONAL { ?property rdfs:range ?range } FILTER (!BOUND(?range)) }"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); SparqlResultSet results = g.ExecuteQuery(q) as SparqlResultSet; if (results != null) { TestTools.ShowResults(results); Assert.IsTrue(results.All(r => !r.HasValue("range") || r["range"] == null), "There should be no values for ?range returned"); } else { Assert.Fail("Did not get a SparqlResultSet as expected"); } }
private SparqlQuery GetRestaurantsQuery() { string query = @"CONSTRUCT WHERE { ?f rdf:type dbo:Restaurant . ?f dbo:cuisine ?cuisine . ?f foaf:homepage ?website . ?f rdfs:label ?name . ?f geo:lat ?latitude . ?f geo:long ?longitude . ?f dbo:address ?address } LIMIT 30"; SparqlParameterizedString queryString = new SparqlParameterizedString(); //Add a namespace declaration queryString.Namespaces.AddNamespace("dbo", new Uri("http://dbpedia.org/ontology/")); queryString.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); queryString.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); queryString.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); queryString.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); queryString.CommandText = query; SparqlQueryParser parser = new SparqlQueryParser(); return parser.ParseFromString(queryString); }
/// <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.QueryText = "SELECT * WHERE {"; int p = 0; foreach (Statement stmt in graph) { //Add Subject queryString.QueryText += "\n"; if (stmt.Subject is Variable) { queryString.QueryText += stmt.Subject.ToString(); } else { queryString.QueryText += "@param" + p; queryString.SetParameter("param" + p, SemWebConverter.FromSemWeb(stmt.Subject, this._mapping)); p++; } queryString.QueryText += " "; //Add Predicate if (stmt.Predicate is Variable) { queryString.QueryText += stmt.Predicate.ToString(); } else { queryString.QueryText += "@param" + p; queryString.SetParameter("param" + p, SemWebConverter.FromSemWeb(stmt.Predicate, this._mapping)); p++; } queryString.QueryText += " "; //Add Object if (stmt.Object is Variable) { queryString.QueryText += stmt.Object.ToString(); } else { queryString.QueryText += "@param" + p; queryString.SetParameter("param" + p, SemWebConverter.FromSemWeb(stmt.Object, this._mapping)); p++; } queryString.QueryText += " ."; } queryString.QueryText += "}"; //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"); } }
/// <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", new Uri(NamespaceMapper.OWL)); context.QNameMapper.AddNamespace("rdf", new Uri(NamespaceMapper.RDF)); context.QNameMapper.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS)); context.QNameMapper.AddNamespace("dc", new Uri("http://purl.org/dc/elements/1.1/")); context.QNameMapper.AddNamespace("dct", new Uri("http://purl.org/dc/terms/")); context.QNameMapper.AddNamespace("vann", new Uri("http://purl.org/vocab/vann/")); context.QNameMapper.AddNamespace("vs", new Uri("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(new Uri(NamespaceMapper.OWL + "Ontology")); IUriNode rdfType = context.Graph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); IUriNode rdfsLabel = context.Graph.CreateUriNode(new Uri(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.ToString()); } context.HtmlWriter.RenderEndTag(); if (!this.Stylesheet.Equals(String.Empty)) { context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, this.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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //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.ToString()); } context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif } } //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.ToString()); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClassUri); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); } switch (authorName.NodeType) { case NodeType.Uri: context.HtmlWriter.WriteEncodedText(((IUriNode)authorName).Uri.ToString()); 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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif } //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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //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).ToString()); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClassUri); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A); context.HtmlWriter.WriteEncodedText(context.QNameMapper.GetNamespaceUri(prefix).ToString()); context.HtmlWriter.RenderEndTag(); context.HtmlWriter.RenderEndTag(); //RDF/XML Syntax context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5); context.HtmlWriter.WriteEncodedText("RDF/XML Syntax"); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%"); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre); 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.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //Turtle/N3 Syntax context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5); context.HtmlWriter.WriteEncodedText("Turtle/N3 Syntax"); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%"); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre); context.HtmlWriter.WriteEncodedText("@prefix " + prefix + ": <" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + "> ."); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //SPARQL Syntax context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5); context.HtmlWriter.WriteEncodedText("SPARQL Syntax"); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%"); context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre); context.HtmlWriter.WriteEncodedText("PREFIX " + prefix + ": <" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + ">"); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif } } } } 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); } } //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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.WriteEncodedText("This Schema defines the following classes:"); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif context.HtmlWriter.AddStyleAttribute("width", "90%"); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.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, this.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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P); context.HtmlWriter.WriteEncodedText("This Schema defines the following properties:"); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif context.HtmlWriter.AddStyleAttribute("width", "90%"); context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.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, this.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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //Show details for each class context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H3); context.HtmlWriter.WriteEncodedText("Classes"); context.HtmlWriter.RenderEndTag(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //Now create the URI Nodes we need for the next stage of Output IUriNode rdfsDomain = context.Graph.CreateUriNode(new Uri(NamespaceMapper.RDFS + "domain")); IUriNode rdfsRange = context.Graph.CreateUriNode(new Uri(NamespaceMapper.RDFS + "range")); IUriNode rdfsSubClassOf = context.Graph.CreateUriNode(new Uri(NamespaceMapper.RDFS + "subClassOf")); IUriNode rdfsSubPropertyOf = context.Graph.CreateUriNode(new Uri(NamespaceMapper.RDFS + "subPropertyOf")); IUriNode owlDisjointClass = context.Graph.CreateUriNode(new Uri(NamespaceMapper.OWL + "disjointWith")); IUriNode owlEquivalentClass = context.Graph.CreateUriNode(new Uri(NamespaceMapper.OWL + "equivalentClass")); IUriNode owlEquivalentProperty = context.Graph.CreateUriNode(new Uri(NamespaceMapper.OWL + "equivalentProperty")); IUriNode owlInverseProperty = context.Graph.CreateUriNode(new Uri(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) { String qname = context.NodeFormatter.Format(r["class"]); //Use a <div> for each Class context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.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 { #if !SILVERLIGHT context.HtmlWriter.WriteEncodedText(temp.Segments.Last()); #else context.HtmlWriter.WriteEncodedText(temp.Segments().Last()); #endif } } 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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //Output further information about the class IEnumerable<Triple> ts; //Output any Subclasses ts = context.Graph.GetTriplesWithSubjectPredicate(rdfsSubClassOf, r["class"]); this.GenerateCaptionedInformation(context, "Has Sub Classes", ts, t => t.Object); //Output Properties which have this as domain/range ts = context.Graph.GetTriplesWithPredicateObject(rdfsDomain, r["class"]); this.GenerateCaptionedInformation(context, "Properties Include", ts, t => t.Subject); ts = context.Graph.GetTriplesWithPredicateObject(rdfsRange, r["class"]); this.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"])); this.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"])); this.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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif } } 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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //Alter our previous getClasses 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) { String qname = context.NodeFormatter.Format(r["property"]); //Use a <div> for each Property context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.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 { #if !SILVERLIGHT context.HtmlWriter.WriteEncodedText(temp.Segments.Last()); #else context.HtmlWriter.WriteEncodedText(temp.Segments().Last()); #endif } } 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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif //Output further information about the property IEnumerable<Triple> ts; //Output any Subproperties ts = context.Graph.GetTriplesWithSubjectPredicate(rdfsSubPropertyOf, r["property"]); this.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); //Output any Equivalent Properties ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], owlEquivalentProperty).Concat(context.Graph.GetTriplesWithPredicateObject(owlEquivalentProperty, r["property"])); this.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"])); this.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(); #if !NO_WEB context.HtmlWriter.WriteLine(); #endif } } 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 }
private void TestBindings(ISparqlDataset data, SparqlParameterizedString queryWithBindings, SparqlParameterizedString queryWithoutBindings) { this.TestBindings(data, queryWithBindings.ToString(), queryWithoutBindings.ToString()); }
/// <summary> /// Loads a Graph from the Store /// </summary> /// <param name="g">Graph to load into</param> /// <param name="graphUri">Uri of the Graph to load</param> /// <remarks> /// If an empty/null Uri is specified then the Default Graph of the Store will be loaded /// </remarks> public void LoadGraph(IGraph g, string graphUri) { try { HttpWebRequest request; Dictionary<String, String> serviceParams = new Dictionary<string, string>(); String tID = (this._activeTrans.Value == null) ? String.Empty : "/" + this._activeTrans.Value; String requestUri = this._kb + tID + "/query"; SparqlParameterizedString construct = new SparqlParameterizedString(); if (!graphUri.Equals(String.Empty)) { construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }"; construct.SetUri("graph", new Uri(graphUri)); if (g.IsEmpty) g.BaseUri = new Uri(graphUri); } else { construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"; } serviceParams.Add("query", construct.ToString()); request = this.CreateRequest(requestUri, MimeTypesHelper.HttpAcceptHeader, "GET", serviceParams); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType); parser.Load(g, new StreamReader(response.GetResponseStream())); response.Close(); } } catch (WebException webEx) { #if DEBUG if (Options.HttpDebugging) { if (webEx.Response != null) Tools.HttpDebugResponse((HttpWebResponse)webEx.Response); } #endif throw new RdfStorageException("A HTTP Error occurred while trying to load a Graph from the Store", webEx); } }
/// <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) { }
/// <summary> /// Creates a new SPARQL View /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="store">Triple Store to query</param> public NativeSparqlView(SparqlParameterizedString sparqlQuery, INativelyQueryableStore store) : this(sparqlQuery.ToString(), store) { }
/// <summary> /// Creates a new SPARQL View. /// </summary> /// <param name="sparqlQuery">SPARQL Query.</param> /// <param name="store">Triple Store to query.</param> public NativeSparqlView(SparqlParameterizedString sparqlQuery, INativelyQueryableStore store) : this(sparqlQuery.ToString(), store) { }
private void TestNegation(ISparqlDataset data, SparqlParameterizedString queryWithNegation, SparqlParameterizedString queryWithoutNegation) { this.TestNegation(data, queryWithNegation.ToString(), queryWithoutNegation.ToString()); }
/// <summary> /// Appends the given query as a sub-query to the existing command text, any prefixes in the sub-query are moved to the parent query but any parameter/variable assignments will be lost /// </summary> /// <param name="query">Query</param> public void AppendSubQuery(SparqlParameterizedString query) { // TODO shouldn't we ensure that the text is wrapped in { } to get a correct subquery pattern ? // this may cause compatibility issues though Append(query); }
public ICollection<BaprLocation> GetFromLinkedGeoData(string text, double latitude, double longitude, IUserPreference userPreference) { var cuisine = BaprAPI.Utils.Utils.GetCuisines(userPreference, false); string searchQueryByText = "SELECT DISTINCT ?lat ?long ?name ?website ?cuisine ?address ?opening_hours ?wheelchair WHERE {\n" + "?s geo:lat ?lat .\n" + "?s geo:long ?long .\n" + "?s rdfs:label ?name. \n" + "?s a ?type. \n" + "OPTIONAL { ?s foaf:homepage ?website .}\n" + "OPTIONAL { ?s lgd:cuisine ?cuisine .}\n" + "OPTIONAL { ?s lgd:address ?address .}\n " + "OPTIONAL { ?s lgd:opening_hours ?opening_hours .}\n " + (userPreference.NeedWheelchair ? "?s lgd:wheelchair ?wheelchair. FILTER (?wheelchair =" + BaprAPI.Models.Constants.xsdBooleanIsTrue + ")\n" : " OPTIONAL {?s lgd:wheelchair ?wheelchair.} \n") + "FILTER (langMatches(lang(?name ), \"en\") \n" + " && ?lat > " + latitude + " - 0.5 && ?lat < " + latitude + " + 0.5 " + " && ?long > " + longitude + " - 0.5 && ?long < " + longitude + " + 0.5\n" + " && contains(lcase(?name),lcase(\"" + text.ToLower() + "\"))\n" + " && ((?type = lgd:Restaurant " + (!string.IsNullOrEmpty(cuisine) ? "&& lcase(?cuisine) in (" + cuisine + ")" : string.Empty) + ") \n" + "|| ?type = lgd:Hospital || ?type = lgd:Bar || ?type = lgd:Bank \n" + "|| ?type = lgd:Pharmacy || ?type = lgd:FastFood || ?type=lgd:Cafe || ?type=lgd:Pub || ?type= lgd:Theatre" + "|| ?type = lgd:Museum))" + "} LIMIT 10"; SparqlParameterizedString sparqlQueryString = new SparqlParameterizedString(); sparqlQueryString.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); sparqlQueryString.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); sparqlQueryString.Namespaces.AddNamespace("lgd", new Uri("http://linkedgeodata.org/ontology/")); sparqlQueryString.Namespaces.AddNamespace("geo", new Uri("http://www.w3.org/2003/01/geo/wgs84_pos#")); sparqlQueryString.Namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); sparqlQueryString.CommandText = searchQueryByText; return BaprAPI.Utils.Utils.ParseSparqlQuery(sparqlQueryString, @"http://linkedgeodata.org/sparql"); }
private void ExpandByDataset(UriToExpand u, ExpansionContext context, ExpansionDataset dataset) { if (u.Depth == context.Profile.MaxExpansionDepth) return; if (dataset.Ignore) return; foreach (Uri endpoint in dataset.SparqlEndpoints) { Thread.Sleep(HttpRequestInterval); SparqlRemoteEndpoint sparqlEndpoint = new SparqlRemoteEndpoint(endpoint); try { SparqlParameterizedString queryString = new SparqlParameterizedString("DESCRIBE @uri"); queryString.SetUri("uri", u.Uri); Object temp = sparqlEndpoint.QueryWithResultGraph(queryString.ToString()); if (temp is Graph) { Graph g = (Graph)temp; this.ExpandGraph(u, g, context); } } catch (RdfException rdfEx) { this.DebugErrors("Error: Tried to DESCRIBE <" + u.Uri.ToString() + "> against the SPARQL Endpoint <" + endpoint.ToString() + "> but an error occurred:", rdfEx); } catch (WebException webEx) { this.DebugErrors("Error: Tried to DESCRIBE <" + u.Uri.ToString() + "> against the SPARQL Endpoint <" + endpoint.ToString() + "> but an error occurred:", webEx); } } foreach (Uri endpoint in dataset.UriLookupEndpoints) { this.ExpandByUriLookup(u, context, endpoint); } foreach (Uri endpoint in dataset.UriDiscoveryEndpoints) { this.ExpandByUriDiscovery(u, context, endpoint); } }
/// <summary> /// Creates a new SPARQL View. /// </summary> /// <param name="sparqlQuery">SPARQL Query.</param> /// <param name="store">Triple Store to query.</param> protected BaseSparqlView(SparqlParameterizedString sparqlQuery, ITripleStore store) : this(sparqlQuery.ToString(), store) { }
/// <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) { }
static void AddExistingItem(IDictionary<RegistrationEntryKey, RegistrationCatalogEntry> resources, TripleStore store, Uri catalogEntry) { Trace.TraceInformation("RegistrationPersistence.AddExistingItem: catalogEntry = {0}", catalogEntry); SparqlParameterizedString sparql = new SparqlParameterizedString(); sparql.CommandText = Utils.GetResource("sparql.ConstructCatalogEntryGraph.rq"); sparql.SetUri("catalogEntry", catalogEntry); IGraph graph = SparqlHelpers.Construct(store, sparql.ToString()); resources.Add(RegistrationCatalogEntry.Promote(catalogEntry.AbsoluteUri, graph)); }
/// <summary> /// Creates a new SPARQL View /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="store">Triple Store to query</param> public BaseSparqlView(SparqlParameterizedString sparqlQuery, ITripleStore store) : this(sparqlQuery.ToString(), store) { }
protected override bool HasTripleInternal(Triple t) { if (this._manager is IQueryableGenericIOManager) { SparqlParameterizedString queryString = new SparqlParameterizedString("ASK WHERE { @subject @predicate @object}"); queryString.SetParameter("subject", t.Subject); queryString.SetParameter("predicate", t.Predicate); queryString.SetParameter("object", t.Object); Object results = ((IQueryableGenericIOManager)this._manager).Query(queryString.ToString()); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; return rset.ResultsType == SparqlResultsType.Boolean && rset.Result; } else { return false; } } else { throw new dotSesameRepo.RepositoryException("This dotNetRDF Generic Repository does not support detecting whether a given Statement exists in the Store"); } }