/// <summary> /// Processes a PATCH operation. /// </summary> /// <param name="context">HTTP Context.</param> public override void ProcessPatch(IHttpContext context) { // Work out the Graph URI we want to patch Uri graphUri = ResolveGraphUri(context); // If the Request has the SPARQL Update MIME Type then we can process it if (context.Request.ContentLength > 0) { if (context.Request.ContentType.Equals("application/sparql-update")) { // Try and parse the SPARQL Update // No error handling here as we assume the calling IHttpHandler does that String patchData; using (StreamReader reader = new StreamReader(context.Request.InputStream)) { patchData = reader.ReadToEnd(); reader.Close(); } SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(patchData); // Assuming that we've got here i.e. the SPARQL Updates are parseable then // we need to check that they actually affect the relevant Graph if (cmds.Commands.All(c => c.AffectsSingleGraph && c.AffectsGraph(graphUri))) { GenericUpdateProcessor processor = new GenericUpdateProcessor(_manager); processor.ProcessCommandSet(cmds); processor.Flush(); } else { // One/More commands either do no affect a Single Graph or don't affect the Graph // implied by the HTTP Request so give a 422 response context.Response.StatusCode = 422; return; } } else { // Don't understand other forms of PATCH requests context.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType; return; } } else { // Empty Request is a Bad Request context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } }
public void SparqlUpdateInsertCommand2() { SparqlParameterizedString command = new SparqlParameterizedString(); command.Namespaces.AddNamespace("rdf", new Uri(NamespaceMapper.RDF)); command.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS)); command.CommandText = "INSERT { ?s rdf:type ?class } USING <http://example.org/temp> WHERE { ?s a ?type . ?type rdfs:subClassOf+ ?class };"; command.CommandText += "INSERT { ?s ?property ?value } USING <http://example.org/temp> WHERE {?s ?p ?value . ?p rdfs:subPropertyOf+ ?property };"; command.CommandText += "INSERT { ?s rdf:type rdfs:Class } USING <http://example.org/temp> WHERE { ?s rdfs:subClassOf ?class };"; command.CommandText += "INSERT { ?s rdf:type rdf:Property } USING <http://example.org/temp> WHERE { ?s rdfs:subPropertyOf ?property };"; TripleStore store = new TripleStore(); Graph g = new Graph(); FileLoader.Load(g, "InferenceTest.ttl"); g.BaseUri = new Uri("http://example.org/temp"); store.Add(g); int origTriples = g.Triples.Count; SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(command); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store); processor.ProcessCommandSet(cmds); Assert.AreEqual(origTriples, g.Triples.Count, "Triples in input Graph shouldn't have changed as INSERTs should have gone to the default graph"); IGraph def = store[null]; TestTools.ShowGraph(def); Console.WriteLine(); //Apply a RDFS reasoner over the original input and output it into another graph //Should be equivalent to the default Graph Graph h = new Graph(); RdfsReasoner reasoner = new RdfsReasoner(); reasoner.Apply(g, h); TestTools.ShowGraph(h); GraphDiffReport report = h.Difference(def); if (!report.AreEqual) { TestTools.ShowDifferences(report); Assert.IsTrue(report.RemovedTriples.Count() == 1, "Should have only 1 missing Triple (due to rdfs:domain inference which is hard to encode in an INSERT command)"); } }
public void SparqlParameterizedString() { String test = @"INSERT DATA { GRAPH @graph { <http://uri> <http://uri> <http://uri> }}"; SparqlParameterizedString cmdString = new SparqlParameterizedString(test); cmdString.SetUri("graph", new Uri("http://example.org/graph")); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(cmdString); cmds.ToString(); }
/// <summary> /// Applies SPARQL Updates to the Store. /// </summary> /// <param name="sparqlUpdate">SPARQL Update.</param> public void Update(String sparqlUpdate) { if (_updateParser == null) { _updateParser = new SparqlUpdateParser(); } SparqlUpdateCommandSet cmds = _updateParser.ParseFromString(sparqlUpdate); if (_updateProcessor == null) { _updateProcessor = new LeviathanUpdateProcessor(_dataset); } _updateProcessor.ProcessCommandSet(cmds); }
private void SparqlMathTest() { const string update = @" DELETE { ?s ?p ?o. } INSERT { ?s ?p ?a. } WHERE { ?s ?p ?o. BIND(?o / 2 AS ?a) } "; const string query = @"SELECT * WHERE { ?s ?p ?o.}"; var graph = new Graph(); graph.Assert(graph.CreateBlankNode(), graph.CreateBlankNode(), 0.5.ToLiteral(graph)); Assert.Equal(0.5, graph.Triples.Select(t => t.Object.AsValuedNode().AsDouble()).First()); var store = new TripleStore(); store.Add(graph); var queryProcessor = new LeviathanQueryProcessor(store); var queryParser = new SparqlQueryParser(); var q = queryParser.ParseFromString(query); var result = q.Process(queryProcessor) as SparqlResultSet; var oNode = result.First()["o"]; Assert.Equal("0.5", ((ILiteralNode)oNode).Value); q = queryParser.ParseFromString("SELECT ?a WHERE { ?s ?p ?o. BIND(?o / 2 AS ?a) }"); //q = queryParser.ParseFromString("SELECT ?a WHERE { BIND (0.25 as ?a) }"); result = q.Process(queryProcessor) as SparqlResultSet; oNode = result.First()["a"]; var o = oNode.AsValuedNode().AsDouble(); Assert.Equal(0.25, o); Assert.Equal("0.25", ((ILiteralNode)oNode).Value); var updateProcessor = new LeviathanUpdateProcessor(store); var updateParser = new SparqlUpdateParser(); updateParser.ParseFromString(update).Process(updateProcessor); result = queryParser.ParseFromString(query).Process(queryProcessor) as SparqlResultSet; oNode = result.First()["o"]; //Assert.Equal("0.25", ((ILiteralNode)oNode).Value); o = oNode.AsValuedNode().AsDouble(); Assert.Equal(0.25, o); //@object is 25 when using German (Germany) regional format //@object is 0.25 when using English (United Kingdom) regional format }
private void TestDropGraphCommit() { ISparqlDataset dataset = this.GetNonEmptyDataset(); String updates = "DROP GRAPH <" + TestGraphUri.ToString() + ">"; SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(updates); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); processor.ProcessCommandSet(cmds); Assert.False(dataset.HasGraph(TestGraphUri), "Graph should not exist"); }
public void ApplyTransaction(IList <Triple> preconditions, IList <Triple> deletePatterns, IList <Triple> inserts, string updateGraphUri) { if (preconditions.Count > 0) { throw new NotSupportedException("SparqlDataObjectStore does not support conditional updates"); } var deleteOp = FormatDeletePatterns(deletePatterns, updateGraphUri); var insertOp = FormatInserts(inserts, updateGraphUri); var parser = new SparqlUpdateParser(); var cmds = parser.ParseFromString(deleteOp + "\n" + insertOp); _updateProcessor.ProcessCommandSet(cmds); }
public void StorageStardogAmpersandsInDataTest() { try { Options.HttpDebugging = true; StardogConnector stardog = StardogTests.GetConnection();; //Save the Graph Graph g = new Graph(); String fragment = "@prefix : <http://example.org/> . [] :string \"This has & ampersands in it\" ."; g.LoadFromString(fragment); g.BaseUri = new Uri("http://example.org/ampersandGraph"); Console.WriteLine("Original Graph:"); TestTools.ShowGraph(g); stardog.SaveGraph(g); //Retrieve and check it round trips Graph h = new Graph(); stardog.LoadGraph(h, g.BaseUri); Console.WriteLine("Graph as retrieved from Stardog:"); TestTools.ShowGraph(h); Assert.AreEqual(g, h, "Graphs should be equal"); //Now try to delete the data from this Graph GenericUpdateProcessor processor = new GenericUpdateProcessor(stardog); SparqlUpdateParser parser = new SparqlUpdateParser(); processor.ProcessCommandSet(parser.ParseFromString("WITH <http://example.org/ampersandGraph> DELETE WHERE { ?s ?p ?o }")); Graph i = new Graph(); stardog.LoadGraph(i, g.BaseUri); Console.WriteLine("Graph as retrieved after the DELETE WHERE:"); TestTools.ShowGraph(i); Assert.AreNotEqual(g, i, "Graphs should not be equal"); Assert.AreNotEqual(h, i, "Graphs should not be equal"); } finally { Options.HttpDebugging = false; } }
public void SparqlUpdateInsertCommand() { SparqlParameterizedString command = new SparqlParameterizedString(); command.Namespaces.AddNamespace("rdf", new Uri(NamespaceMapper.RDF)); command.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS)); command.CommandText = "INSERT { ?s rdf:type ?class } WHERE { ?s a ?type . ?type rdfs:subClassOf+ ?class };"; command.CommandText += "INSERT { ?s ?property ?value } WHERE {?s ?p ?value . ?p rdfs:subPropertyOf+ ?property };"; command.CommandText += "INSERT { ?s rdf:type rdfs:Class } WHERE { ?s rdfs:subClassOf ?class };"; command.CommandText += "INSERT { ?s rdf:type rdf:Property } WHERE { ?s rdfs:subPropertyOf ?property };"; TripleStore store = new TripleStore(); Graph g = new Graph(); FileLoader.Load(g, "InferenceTest.ttl"); g.Retract(g.Triples.Where(t => !t.IsGroundTriple).ToList()); g.BaseUri = null; store.Add(g); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(command); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store); processor.ProcessCommandSet(cmds); TestTools.ShowGraph(g); Console.WriteLine(); //Now reload the test data and apply an RDFS reasoner over it //This should give us a Graph equivalent to the one created by the previous INSERT commands Graph h = new Graph(); FileLoader.Load(h, "InferenceTest.ttl"); h.Retract(h.Triples.Where(t => !t.IsGroundTriple).ToList()); RdfsReasoner reasoner = new RdfsReasoner(); reasoner.Apply(h); GraphDiffReport diff = h.Difference(g); if (!diff.AreEqual) { TestTools.ShowDifferences(diff); } Assert.AreEqual(h, g, "Graphs should be equal"); }
public void UpdateTripleStore(SparqlParameterizedString updateString) { if (_transaction != null) { _transaction.AddUpdateString(updateString); } else { var processor = new LeviathanUpdateProcessor(_dataset); var sparqlParser = new SparqlUpdateParser(); AddAllColidNamespaces(updateString); var query = sparqlParser.ParseFromString(updateString); processor.ProcessCommandSet(query); } }
/// <summary> /// Makes a SPARQL Update against the store /// </summary> /// <param name="sparqlUpdate">SPARQL Update</param> public void Update(string sparqlUpdate) { if (!this._skipLocalParsing) { //Parse the update locally to validate it //This also saves us wasting a HttpWebRequest on a malformed update SparqlUpdateParser uparser = new SparqlUpdateParser(); uparser.ParseFromString(sparqlUpdate); this._updateEndpoint.Update(sparqlUpdate); } else { //If we're skipping local parsing then we'll need to just make a raw update this._updateEndpoint.Update(sparqlUpdate); } }
public void SparqlUpdateWithCustomQueryProcessor() { Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); g.BaseUri = null; TripleStore store = new TripleStore(); store.Add(g); InMemoryDataset dataset = new InMemoryDataset(store); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString("DELETE { ?s a ?type } WHERE { ?s a ?type }"); ISparqlUpdateProcessor processor = new ExplainUpdateProcessor(dataset, ExplanationLevel.Full); processor.ProcessCommandSet(cmds); }
public void SparqlUpdateDeleteDataCombination() { SparqlParameterizedString command = new SparqlParameterizedString(); command.Namespaces.AddNamespace("ex", new Uri("http://example.org/")); command.CommandText = "DELETE DATA { ex:a ex:b ex:c GRAPH <http://example.org/graph> { ex:a ex:b ex:c } }"; SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(command); Assert.IsFalse(cmds.Commands.All(cmd => cmd.AffectsSingleGraph), "Commands should report that they do not affect a single Graph"); Assert.IsTrue(cmds.Commands.All(cmd => cmd.AffectsGraph(null)), "Commands should report that they affect the Default Graph"); Assert.IsTrue(cmds.Commands.All(cmd => cmd.AffectsGraph(new Uri("http://example.org/graph"))), "Commands should report that they affect the named Graph"); InMemoryDataset dataset = new InMemoryDataset(); IGraph def = new Graph(); def.NamespaceMap.Import(command.Namespaces); def.Assert(new Triple(def.CreateUriNode("ex:a"), def.CreateUriNode("ex:b"), def.CreateUriNode("ex:c"))); dataset.AddGraph(def); IGraph ex = new Graph(); ex.BaseUri = new Uri("http://example.org/graph"); ex.NamespaceMap.Import(command.Namespaces); ex.Assert(new Triple(ex.CreateUriNode("ex:a"), ex.CreateUriNode("ex:b"), ex.CreateUriNode("ex:c"))); dataset.AddGraph(ex); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); processor.ProcessCommandSet(cmds); Graph g = new Graph(); g.NamespaceMap.Import(command.Namespaces); Triple t = new Triple(g.CreateUriNode("ex:a"), g.CreateUriNode("ex:b"), g.CreateUriNode("ex:c")); def = dataset[null]; Assert.AreEqual(0, def.Triples.Count, "Should be 0 Triples in the Default Graph"); Assert.IsFalse(def.ContainsTriple(t), "Should not have the deleted Triple in the Default Graph"); ex = dataset[new Uri("http://example.org/graph")]; Assert.AreEqual(0, ex.Triples.Count, "Should be 0 Triples in the Named Graph"); Assert.IsFalse(ex.ContainsTriple(t), "Should not have the deleted Triple in the Named Graph"); }
public bool ApplyScript(Script script) { var ps = new SparqlParameterizedString(); ps.CommandText = script.Contents; var parser = new SparqlUpdateParser(); var query = parser.ParseFromString(ps); try { query.Process(_updateProcessor); } catch (Exception e) { Console.WriteLine(e); return(false); } return(true); }
public void UpdateGraph(Uri graphUri, GraphDiffReport difference) { ModifyCommand modifyCommand = difference.AsUpdate(); SparqlUpdateParser parser = new SparqlUpdateParser(); parser.ParseFromString(modifyCommand.ToString()); HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{BaseUri}{this._repositoriesPrefix}Master{this._updatePath}"); request.Method = "POST"; request.ContentType = "application/sparql-update"; request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); request.Headers.Add("Api-Version", apiVersion); using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), new UTF8Encoding(Options.UseBomForUtf8))) { writer.Write(EscapeQuery(modifyCommand.ToString())); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Dispose(); }
public void SparqlDatasetDefaultGraphManagementWithUpdate() { TripleStore store = new TripleStore(); Graph g = new Graph(); store.Add(g); Graph h = new Graph(); h.BaseUri = new Uri("http://example.org/someOtherGraph"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store, h.BaseUri); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString("LOAD <http://www.dotnetrdf.org/configuration#>"); processor.ProcessCommandSet(cmds); Assert.True(g.IsEmpty, "Graph with null URI (normally the default Graph) should be empty as the Default Graph for the Dataset should have been a named Graph so this Graph should not have been filled by the LOAD Command"); Assert.False(h.IsEmpty, "Graph with name should be non-empty as it should have been the Default Graph for the Dataset and so filled by the LOAD Command"); }
public void ApplyTransaction(IEnumerable <ITriple> existencePreconditions, IEnumerable <ITriple> nonexistencePreconditions, IEnumerable <ITriple> deletePatterns, IEnumerable <ITriple> inserts, string updateGraphUri) { if (existencePreconditions.Any()) { throw new NotSupportedException("SparqlDataObjectStore does not support conditional updates"); } if (nonexistencePreconditions.Any()) { // NOTE: At the moment this is ignored because if you use key properties, // non-existence preconditions will get generated and we want to support // using key properties with SPARQL update endpoints. } var deleteOp = FormatDeletePatterns(deletePatterns.ToList(), updateGraphUri); var insertOp = FormatInserts(inserts, updateGraphUri); var parser = new SparqlUpdateParser(); var cmds = parser.ParseFromString(deleteOp + "\n" + insertOp); _updateProcessor.ProcessCommandSet(cmds); }
public void SparqlUpdateModify() { TripleStore store = new TripleStore(); Graph g = new Graph(); FileLoader.Load(g, "resources\\InferenceTest.ttl"); g.BaseUri = null; store.Add(g); IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); Assert.NotEmpty(store.GetTriplesWithPredicate(rdfType)); String update = "DELETE {?s a ?type} WHERE {?s a ?type}"; SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(update); store.ExecuteUpdate(cmds); Assert.Empty(store.GetTriplesWithPredicate(rdfType)); }
public void SparqlUpdateModify() { TripleStore store = new TripleStore(); Graph g = new Graph(); FileLoader.Load(g, "InferenceTest.ttl"); g.BaseUri = null; store.Add(g); IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); Assert.AreNotEqual(0, store.GetTriplesWithPredicate(rdfType).Count(), "Store should contain some rdf:type Triples"); String update = "DELETE {?s a ?type} WHERE {?s a ?type}"; SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString(update); store.ExecuteUpdate(cmds); Assert.AreEqual(0, store.GetTriplesWithPredicate(rdfType).Count(), "Store should contain no rdf:type Triples after DELETE command executes"); }
public void SparqlDatasetDefaultGraphManagementWithUpdate2() { TripleStore store = new TripleStore(); Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/graph"); store.Add(g); Graph h = new Graph(); h.BaseUri = new Uri("http://example.org/someOtherGraph"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store, h.BaseUri); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString("LOAD <http://www.dotnetrdf.org/configuration#> INTO GRAPH <http://example.org/graph>"); processor.ProcessCommandSet(cmds); Assert.False(g.IsEmpty, "First Graph should not be empty as should have been filled by the LOAD command"); Assert.True(h.IsEmpty, "Second Graph should be empty as should not have been filled by the LOAD command"); }
/// <summary> /// Elimina los triples http://purl.org/roh/mirror/foaf#primaryTopic del RDF a cargar y los triples que tenían cagados en la BBDD /// </summary> /// <param name="pDataGraph">Grafo con los datos a cargar</param> /// <returns>Lista de grafos afectados</returns> private HashSet <string> RemovePrimaryTopics(ref RohGraph pDataGraph) { HashSet <string> graphs = new HashSet <string>(); List <string> mainEntities = new List <string>(); string query = @"select distinct * where{?s <http://purl.org/roh/mirror/foaf#primaryTopic> ""true""^^<http://www.w3.org/2001/XMLSchema#boolean>}"; SparqlResultSet sparqlResultSet = (SparqlResultSet)pDataGraph.ExecuteQuery(query.ToString()); foreach (SparqlResult sparqlResult in sparqlResultSet.Results) { mainEntities.Add(sparqlResult["s"].ToString()); } //Se eliminan todas las referncias a las entidades principales if (mainEntities.Count > 0) { foreach (string mainEntity in mainEntities) { graphs.UnionWith(DeleteUpdatedEntity(mainEntity)); } } //Eliminamos el triple que marca las entidades principales para que no se inserte en la BBDD { TripleStore store = new TripleStore(); store.Add(pDataGraph); SparqlUpdateParser parser = new SparqlUpdateParser(); //Actualizamos los sujetos SparqlUpdateCommandSet updateSubject = parser.ParseFromString( @" DELETE { ?s ?p ?o. } WHERE { ?s ?p ?o. FILTER(?p =<http://purl.org/roh/mirror/foaf#primaryTopic>) }"); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store); processor.ProcessCommandSet(updateSubject); } return(graphs); }
public void SparqlDatasetDefaultGraphManagementWithUpdate5() { TripleStore store = new TripleStore(); Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/graph"); store.Add(g); Graph h = new Graph(); h.BaseUri = new Uri("http://example.org/someOtherGraph"); store.Add(h); InMemoryDataset dataset = new InMemoryDataset(store, h.BaseUri); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet cmds = parser.ParseFromString("LOAD <http://www.dotnetrdf.org/configuration#>; WITH <http://example.org/graph> INSERT { ?s a ?type } USING <http://example.org/someOtherGraph> WHERE { ?s a ?type }; DELETE WHERE { ?s a ?type }"); processor.ProcessCommandSet(cmds); Assert.False(g.IsEmpty, "First Graph should not be empty as should have been filled by the INSERT command"); Assert.False(h.IsEmpty, "Second Graph should not be empty as should not have been filled by the LOAD command"); Assert.False(h.HasSubGraph(g), "First Graph should not be a subgraph of the Second Graph as the DELETE should have eliminated the subgraph relationship"); }
public void SparqlUpdateMoveCommand3() { IGraph g = new Graph(); FileLoader.Load(g, "InferenceTest.ttl"); g.BaseUri = null; IGraph h = new Graph(); FileLoader.Load(h, "Turtle.ttl"); h.BaseUri = new Uri("http://example.org/destination"); TripleStore store = new TripleStore(); store.Add(g); store.Add(h); Assert.AreNotEqual(g, h, "Graphs should not be equal"); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet commands = parser.ParseFromString("MOVE DEFAULT TO GRAPH <http://example.org/destination>"); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store); processor.ProcessCommandSet(commands); g = store.HasGraph(null) ? store[null] : null; h = store[new Uri("http://example.org/destination")]; Assert.IsFalse(h.IsEmpty, "Destination Graph should not be empty"); Assert.IsFalse(g == null, "Default Graph should still exist"); Assert.IsTrue(g.IsEmpty, "Source Graph (the Default Graph) should be Empty"); Graph orig = new Graph(); FileLoader.Load(orig, "InferenceTest.ttl"); Assert.AreEqual(orig, h, "Destination Graph should be equal to the original contents of the Source Graph"); }
public void OnNewScriptApplication(CurrentState currentState, Migration mig) { var ps = new SparqlParameterizedString(); ps.CommandText = @" PREFIX mig: <http://industrialinference.com/migrations/0.1#> INSERT DATA { GRAPH mig:migrations { _:mig a mig:Migration ; mig:ordinal @ordinal ; mig:dtApplied @dtApplied ; mig:appliedBy @appliedBy ; mig:migrationHash @migrationHash; mig:migratorVersion @migratorVersion; mig:originalPath @originalPath . } }"; ps.SetLiteral("ordinal", mig.ordinal); ps.SetLiteral("dtApplied", mig.dtApplied); ps.SetLiteral("appliedBy", mig.appliedBy); ps.SetLiteral("migrationHash", mig.migrationHash); ps.SetLiteral("migratorVersion", mig.migratorVersion); ps.SetLiteral("originalPath", mig.originalPath); var parser = new SparqlUpdateParser(); var query = parser.ParseFromString(ps); try { query.Process(_updateProcessor); } catch (Exception e) { Console.WriteLine(e); throw; } }
private IEnumerable <SparqlUpdateCommand> GetParsedCommands(SparqlParameterizedString commandString) { var result = _parser.ParseFromString(commandString).Commands; var toBeRemoved = new List <SparqlUpdateCommand>(); foreach (var command in result) { var deleteCommand = command as DeleteCommand; if (deleteCommand != null) { SanitizeDeleteCommand(toBeRemoved, deleteCommand); continue; } var insertDataCommand = command as InsertDataCommand; if (insertDataCommand != null) { SanitizeInsertDataCommand(toBeRemoved, insertDataCommand); } } return(result.Except(toBeRemoved)); }
public void SparqlUpdateMoveCommand2() { IGraph g = new Graph(); FileLoader.Load(g, "resources\\InferenceTest.ttl"); g.BaseUri = new Uri("http://example.org/source"); IGraph h = new Graph(); FileLoader.Load(h, "resources\\Turtle.ttl"); h.BaseUri = null; TripleStore store = new TripleStore(); store.Add(g); store.Add(h); Assert.NotEqual(g, h); SparqlUpdateParser parser = new SparqlUpdateParser(); SparqlUpdateCommandSet commands = parser.ParseFromString("MOVE GRAPH <http://example.org/source> TO DEFAULT"); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(store); processor.ProcessCommandSet(commands); g = store.HasGraph(new Uri("http://example.org/source")) ? store[new Uri("http://example.org/source")] : null; h = store[null]; Assert.False(h.IsEmpty, "Destination Graph should not be empty"); Assert.True(g == null || g.IsEmpty, "Source Graph should be Deleted/Empty"); Graph orig = new Graph(); FileLoader.Load(orig, "resources\\InferenceTest.ttl"); Assert.Equal(orig, h); }
/// <summary> /// Processes SPARQL Update requests /// </summary> /// <param name="context">HTTP Context</param> public void ProcessRequest(HttpContext context) { this._config = this.LoadConfig(context); WebContext webContext = new WebContext(context); // Add our Standard Headers HandlerHelper.AddStandardHeaders(webContext, this._config); // Options we need to determine based on the HTTP Method used String[] updates; String updateText = null; List <String> userDefaultGraphs = new List <String>(); List <String> userNamedGraphs = new List <String>(); try { // Decide what to do based on the HTTP Method switch (context.Request.HttpMethod.ToUpper()) { case "OPTIONS": // OPTIONS requests always result in the Service Description document IGraph svcDescrip = SparqlServiceDescriber.GetServiceDescription(this._config, UriFactory.Create(context.Request.Url.AbsoluteUri)); HandlerHelper.SendToClient(webContext, svcDescrip, this._config); return; case "HEAD": // Just return from a HEAD request return; case "GET": // A GET with an update parameter is a Bad Request updates = context.Request.QueryString.GetValues("update"); if (updates != null && updates.Length > 0) { throw new ArgumentException("Updates cannot be submitted as GET requests"); } // Otherwise GET either results in the Service Description if appropriately conneg'd or // the update form if enabled try { // If we might show the Update Form only show the Description if the selected writer is // not a HTML writer MimeTypeDefinition definition = MimeTypesHelper.GetDefinitions(webContext.GetAcceptTypes()).FirstOrDefault(d => d.CanWriteRdf); if (definition != null) { IRdfWriter writer = definition.GetRdfWriter(); if (!(writer is IHtmlWriter)) { // If not a HTML Writer selected then show the Service Description Graph // unless an error occurs creating it IGraph serviceDescrip = SparqlServiceDescriber.GetServiceDescription(this._config, UriFactory.Create(context.Request.Url.AbsoluteUri)); context.Response.ContentType = definition.CanonicalMimeType; context.Response.ContentEncoding = definition.Encoding; writer.Save(serviceDescrip, new StreamWriter(context.Response.OutputStream, definition.Encoding)); return; } } } catch { // Ignore Exceptions - we'll just show the Query Form or return a 400 Bad Request instead } // If a Writer can't be selected then we'll either show the Update Form or return a 400 Bad Request if (this._config.ShowUpdateForm) { this.ShowUpdateForm(context); } else { throw new ArgumentException("Updates cannot be submitted as GET requests"); } return; case "POST": if (context.Request.ContentType != null) { MimeTypeSelector contentType = MimeTypeSelector.Create(context.Request.ContentType, 0); if (contentType.Type.Equals(MimeTypesHelper.WWWFormURLEncoded)) { // Form URL Encoded was declared type so expect an update parameter in the Form parameters updates = context.Request.Form.GetValues("update"); if (updates == null) { throw new ArgumentException("Required update parameter in POST body was missing"); } if (updates.Length == 0) { throw new ArgumentException("Required update parameter in POST body was missing"); } if (updates.Length > 1) { throw new ArgumentException("The update parameter was specified multiple times in the POST body"); } updateText = updates[0]; // For Form URL Encoded the Using/Using Named Graphs may be specified by Form parameters // Get the USING URIs (if any) if (context.Request.Form["using-graph-uri"] != null) { userDefaultGraphs.AddRange(context.Request.Form.GetValues("using-graph-uri")); } // Get the USING NAMED URIs (if any) if (context.Request.Form["using-named-graph-uri"] != null) { userNamedGraphs.AddRange(context.Request.Form.GetValues("using-named-graph-uri")); } break; } else if (contentType.Type.Equals(MimeTypesHelper.SparqlUpdate)) { // application/sparql-update was declared type so expect utf-8 charset (if present) if (contentType.Charset != null && !contentType.Charset.ToLower().Equals(MimeTypesHelper.CharsetUtf8)) { throw new ArgumentException("HTTP POST request was received with a " + MimeTypesHelper.SparqlUpdate + " Content-Type but a non UTF-8 charset parameter"); } using (StreamReader reader = new StreamReader(context.Request.InputStream)) { updateText = reader.ReadToEnd(); reader.Close(); } // For application/sparql-update the Using/Using Named Graphs may be specified by querystring parameters // Get the USING URIs (if any) if (context.Request.QueryString["using-graph-uri"] != null) { userDefaultGraphs.AddRange(context.Request.QueryString.GetValues("using-graph-uri")); } // Get the USING NAMED URIs (if any) if (context.Request.QueryString["using-named-graph-uri"] != null) { userNamedGraphs.AddRange(context.Request.QueryString.GetValues("using-named-graph-uri")); } break; } else { throw new ArgumentException("HTTP POST made to SPARQL update endpoint had an invalid Content-Type header, only " + MimeTypesHelper.WWWFormURLEncoded + " and " + MimeTypesHelper.SparqlUpdate + " are acceptable"); } } throw new ArgumentException("HTTP POST made to SPARQL Query endpoint was missing the required Content-Type header"); default: throw new NotSupportedException("HTTP " + context.Request.HttpMethod.ToUpper() + " is not supported by a SPARQL Update endpoint"); } // Clean up protocol provided dataset userDefaultGraphs.RemoveAll(g => String.IsNullOrEmpty(g)); userNamedGraphs.RemoveAll(g => String.IsNullOrEmpty(g)); // Now we're going to parse the Updates SparqlUpdateParser parser = new SparqlUpdateParser(); parser.DefaultBaseUri = context.Request.Url; parser.ExpressionFactories = this._config.ExpressionFactories; SparqlUpdateCommandSet commands = parser.ParseFromString(updateText); // Check whether we need to use authentication // If there are no user groups then no authentication is in use so we default to authenticated with no per-action authentication needed bool isAuth = true, requireActionAuth = false; if (this._config.UserGroups.Any()) { // If we have user isAuth = HandlerHelper.IsAuthenticated(webContext, this._config.UserGroups); requireActionAuth = true; } if (!isAuth) { return; } // First check actions to see whether they are all permissible and apply USING/USING NAMED parameters foreach (SparqlUpdateCommand cmd in commands.Commands) { // Authenticate each action bool actionAuth = true; if (requireActionAuth) { actionAuth = HandlerHelper.IsAuthenticated(webContext, this._config.UserGroups, this.GetPermissionAction(cmd)); } if (!actionAuth) { throw new SparqlUpdatePermissionException("You are not authorised to perform the " + this.GetPermissionAction(cmd) + " action"); } // Check whether we need to (and are permitted to) apply USING/USING NAMED parameters if (userDefaultGraphs.Count > 0 || userNamedGraphs.Count > 0) { BaseModificationCommand modify = cmd as BaseModificationCommand; if (modify != null) { if (modify.GraphUri != null || modify.UsingUris.Any() || modify.UsingNamedUris.Any()) { // Invalid if a command already has a WITH/USING/USING NAMED throw new SparqlUpdateMalformedException("A command in your update request contains a WITH/USING/USING NAMED clause but you have also specified one/both of the using-graph-uri or using-named-graph-uri parameters which is not permitted by the SPARQL Protocol"); } else { // Otherwise go ahead and apply userDefaultGraphs.ForEach(u => modify.AddUsingUri(UriFactory.Create(u))); userNamedGraphs.ForEach(u => modify.AddUsingNamedUri(UriFactory.Create(u))); } } } } // Then assuming we got here this means all our actions are permitted so now we can process the updates this.ProcessUpdates(commands); // Flush outstanding changes this._config.Processor.Flush(); // Update the Cache as the request may have changed the endpoint this.UpdateConfig(context); } catch (RdfParseException parseEx) { HandleErrors(context, "Parsing Error", updateText, parseEx, (int)HttpStatusCode.BadRequest); } catch (SparqlUpdatePermissionException permEx) { HandleErrors(context, "Permissions Error", updateText, permEx, (int)HttpStatusCode.Forbidden); } catch (SparqlUpdateMalformedException malEx) { HandleErrors(context, "Malformed Update Error", updateText, malEx, (int)HttpStatusCode.BadRequest); } catch (SparqlUpdateException updateEx) { HandleErrors(context, "Update Error", updateText, updateEx); } catch (RdfException rdfEx) { HandleErrors(context, "RDF Error", updateText, rdfEx); } catch (NotSupportedException notSupEx) { HandleErrors(context, "HTTP Request Error", null, notSupEx, (int)HttpStatusCode.MethodNotAllowed); } catch (ArgumentException argEx) { HandleErrors(context, "HTTP Request Error", null, argEx, (int)HttpStatusCode.BadRequest); } catch (Exception ex) { HandleErrors(context, "Error", updateText, ex); } }
public void SparqlUpdateInsertDeleteWithBlankNodes() { //This test adapted from a contribution by Tomasz Pluskiewicz //It demonstrates an issue in SPARQL Update caused by incorrect Graph //references that can result when using GraphPersistenceWrapper in a SPARQL Update String initData = @"@prefix ex: <http://www.example.com/>. @prefix rr: <http://www.w3.org/ns/r2rml#>. ex:triplesMap rr:predicateObjectMap _:blank . _:blank rr:object ex:Employee, ex:Worker ."; String update = @"PREFIX rr: <http://www.w3.org/ns/r2rml#> DELETE { ?map rr:object ?value . } INSERT { ?map rr:objectMap [ rr:constant ?value ] . } WHERE { ?map rr:object ?value }"; String query = @"prefix ex: <http://www.example.com/> prefix rr: <http://www.w3.org/ns/r2rml#> select * where { ex:triplesMap rr:predicateObjectMap ?predObjMap . ?predObjMap rr:objectMap ?objMap . }"; String expectedData = @"@prefix ex: <http://www.example.com/>. @prefix rr: <http://www.w3.org/ns/r2rml#>. ex:triplesMap rr:predicateObjectMap _:blank. _:blank rr:objectMap _:autos1. _:autos1 rr:constant ex:Employee. _:autos2 rr:constant ex:Worker. _:blank rr:objectMap _:autos2."; // given IGraph graph = new Graph(); graph.LoadFromString(initData); IGraph expectedGraph = new Graph(); expectedGraph.LoadFromString(expectedData); Console.WriteLine("Initial Graph:"); TestTools.ShowGraph(graph); Console.WriteLine(); // when TripleStore store = new TripleStore(); store.Add(graph); var dataset = new InMemoryDataset(store, graph.BaseUri); ISparqlUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); var updateParser = new SparqlUpdateParser(); processor.ProcessCommandSet(updateParser.ParseFromString(update)); Console.WriteLine("Resulting Graph:"); TestTools.ShowGraph(graph); Console.WriteLine(); Triple x = graph.GetTriplesWithPredicate(graph.CreateUriNode("rr:predicateObjectMap")).FirstOrDefault(); INode origBNode = x.Object; Assert.True(graph.GetTriples(origBNode).Count() > 1, "Should be more than one Triple using the BNode"); IEnumerable <Triple> ys = graph.GetTriplesWithSubject(origBNode); foreach (Triple y in ys) { Assert.Equal(origBNode, y.Subject); } //Graphs should be equal GraphDiffReport diff = graph.Difference(expectedGraph); if (!diff.AreEqual) { TestTools.ShowDifferences(diff); } Assert.Equal(expectedGraph, graph); //Test the Query SparqlResultSet results = graph.ExecuteQuery(query) as SparqlResultSet; TestTools.ShowResults(results); Assert.False(results.IsEmpty, "Should be some results"); }
private void SparqlQueryAndUpdateThreadSafeEvaluationActual() { var query1 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/1> { ?s ?p ?o } }"; var query2 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/2> { ?s ?p ?o } }"; var query3 = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/3> { ?s ?p ?o } }"; var update1 = "INSERT DATA { GRAPH <http://example.org/3> { <ex:subj> <ex:pred> <ex:obj> } }"; var q1 = _parser.ParseFromString(query1); var q2 = _parser.ParseFromString(query2); var q3 = _parser.ParseFromString(query3); Assert.False(q1.UsesDefaultDataset, "Query 1 should not be thread safe"); Assert.False(q2.UsesDefaultDataset, "Query 2 should not be thread safe"); Assert.False(q3.UsesDefaultDataset, "Query 3 should not be thread safe"); var parser = new SparqlUpdateParser(); var cmds = parser.ParseFromString(update1); var dataset = new InMemoryDataset(); var g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); g.BaseUri = new Uri("http://example.org/1"); var h = new Graph(); h.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.LeviathanFunctionLibrary.ttl"); h.BaseUri = new Uri("http://example.org/2"); var i = new Graph { BaseUri = new Uri("http://example.org/3") }; dataset.AddGraph(g); dataset.AddGraph(h); dataset.AddGraph(i); var processor = new LeviathanQueryProcessor(dataset); var upProcessor = new LeviathanUpdateProcessor(dataset); var d = new QueryWithGraphDelegate(QueryWithGraph); var d2 = new RunUpdateDelegate(RunUpdate); var t1 = Task.Factory.StartNew(() => QueryWithGraph(q1, processor)); var t2 = Task.Factory.StartNew(() => QueryWithGraph(q2, processor)); var t3 = Task.Factory.StartNew(() => QueryWithGraph(q3, processor)); var t4 = Task.Factory.StartNew(() => RunUpdate(cmds, upProcessor)); Task.WaitAll(t1, t2, t3, t4); var gQuery = t1.Result; var hQuery = t2.Result; var iQuery = t3.Result; Assert.Equal(g, gQuery); Assert.Equal(h, hQuery); if (iQuery.IsEmpty) { _output.WriteLine("Query 3 executed before the INSERT DATA command - running again to get the resulting graph"); iQuery = QueryWithGraph(q3, processor); } else { _output.WriteLine("Query 3 executed after the INSERT DATA command"); } //Test iQuery against an empty Graph Assert.False(iQuery.IsEmpty, "Graph should not be empty as INSERT DATA should have inserted a Triple"); Assert.NotEqual(new Graph(), iQuery); Assert.NotEqual(g, h); }
/// <summary> /// Attempt to auto-detect the syntax of the current document using the filename as a guide /// </summary> public void AutoDetectSyntax(String filename) { if (this._editor == null) { return; //Not yet ready } if (filename == null || System.IO.Path.GetExtension(filename).Equals(String.Empty)) { try { //First see if it's an RDF format IRdfReader parser = StringParser.GetParser(this._editor.Text); if (parser is NTriplesParser) { //NTriples is the fallback so if we get this check if it's actually SPARQL Results try { ISparqlResultsReader sparqlParser = StringParser.GetResultSetParser(this._editor.Text); } catch (RdfParserSelectionException) { //Not a valid SPARQL Results format - may be a SPARQL Query or a SPARQL Update? SparqlQueryParser queryParser = new SparqlQueryParser(SparqlQuerySyntax.Sparql_1_1); try { SparqlQuery q = queryParser.ParseFromString(this._editor.Text); this.SetHighlighter("SparqlQuery11"); } catch (RdfParseException) { //Not a valid SPARQL Query - valid SPARQL Update? SparqlUpdateParser updateParser = new SparqlUpdateParser(); try { SparqlUpdateCommandSet cmds = updateParser.ParseFromString(this._editor.Text); this.SetHighlighter("SparqlUpdate11"); } catch (RdfParseException) { //Was probably actually NTriples this.SetHighlighter(parser); } } } } else { //Got a non NTriples RDF parser so use that to set Highlighter this.SetHighlighter(parser); } } catch (RdfParserSelectionException) { this.SetNoHighlighting(); } return; } try { IHighlightingDefinition def = HighlightingManager.Instance.GetDefinitionByExtension(System.IO.Path.GetExtension(filename)); if (this._enableHighlighting) { this._editor.SyntaxHighlighting = def; } if (def != null) { this._currSyntax = def.Name; this.SetCurrentHighlighterChecked(def.Name); this.SetCurrentValidator(def.Name); this.SetCurrentAutoCompleter(def.Name); } else { this.SetNoHighlighting(); } } catch { this.SetNoHighlighting(); } }