/// <summary> /// Updates the store asynchronously /// </summary> /// <param name="sparqlUpdates">SPARQL Update</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public void Update(string sparqlUpdates, AsyncStorageCallback callback, object state) { this.AsyncUpdate(sparqlUpdates, callback, state); }
/// <summary> /// Gets all available templates for creating a new Store /// </summary> /// <param name="id">Store ID</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to callback</param> /// <returns></returns> public override void GetAvailableTemplates(String id, AsyncStorageCallback callback, Object state) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.AvailableTemplates, id, new IStoreTemplate[] { new StoreTemplate(id) }), state); }
/// <summary> /// Queries the store asynchronously /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery, AsyncStorageCallback callback, object state) { try { //First off parse the Query to see what kind of query it is SparqlQuery q; try { q = this._parser.ParseFromString(sparqlQuery); } catch (RdfParseException parseEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, parseEx), state); return; } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, new RdfStorageException("An unexpected error occurred while trying to parse the SPARQL Query prior to sending it to the Store, see inner exception for details", ex)), state); return; } //Now select the Accept Header based on the query type String accept = (SparqlSpecsHelper.IsSelectQuery(q.QueryType) || q.QueryType == SparqlQueryType.Ask) ? MimeTypesHelper.HttpSparqlAcceptHeader : MimeTypesHelper.HttpAcceptHeader; //Create the Request, for simplicity async requests are always POST HttpWebRequest request; Dictionary <String, String> queryParams = new Dictionary <string, string>(); request = this.CreateRequest("/sparql", accept, "POST", queryParams); request.ContentType = MimeTypesHelper.WWWFormURLEncoded; Tools.HttpDebugRequest(request); request.BeginGetRequestStream(r => { try { Stream stream = request.EndGetRequestStream(r); using (StreamWriter writer = new StreamWriter(stream)) { writer.Write("query="); writer.Write(HttpUtility.UrlEncode(sparqlQuery)); writer.Close(); } request.BeginGetResponse(r2 => { //Get the Response and process based on the Content Type try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2); Tools.HttpDebugResponse(response); StreamReader data = new StreamReader(response.GetResponseStream()); String ctype = response.ContentType; if (SparqlSpecsHelper.IsSelectQuery(q.QueryType) || q.QueryType == SparqlQueryType.Ask) { //ASK/SELECT should return SPARQL Results ISparqlResultsReader resreader = MimeTypesHelper.GetSparqlParser(ctype, q.QueryType == SparqlQueryType.Ask); resreader.Load(resultsHandler, data); response.Close(); } else { //CONSTRUCT/DESCRIBE should return a Graph IRdfReader rdfreader = MimeTypesHelper.GetParser(ctype); rdfreader.Load(rdfHandler, data); response.Close(); } } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }
/// <summary> /// Queries the store asynchronously /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public void Query(string sparqlQuery, AsyncStorageCallback callback, object state) { this.AsyncQuery(sparqlQuery, callback, state); }
/// <summary> /// Loads a Graph from the Store asynchronously /// </summary> /// <param name="handler">Handler to load with</param> /// <param name="graphUri">URI of the Graph to load</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void LoadGraph(IRdfHandler handler, string graphUri, AsyncStorageCallback callback, object state) { try { HttpWebRequest request; Dictionary<String, String> serviceParams = new Dictionary<string, string>(); Uri baseUri = null; SparqlParameterizedString construct = new SparqlParameterizedString(); if (!graphUri.Equals(string.Empty)) { construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }"; baseUri = UriFactory.Create(graphUri); construct.SetUri("graph", baseUri); } else { construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"; } serviceParams.Add("query", construct.ToString()); request = this.CreateRequest("/sparql", MimeTypesHelper.HttpAcceptHeader, "GET", serviceParams); Tools.HttpDebugRequest(request); request.BeginGetResponse(r => { try { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r)) { Tools.HttpDebugResponse(response); IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType); parser.Load(handler, new StreamReader(response.GetResponseStream())); if (baseUri != null) { handler.StartRdf(); handler.HandleBaseUri(baseUri); handler.EndRdf(true); } response.Close(); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler), state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleHttpError(webEx, "loading a Graph from")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleError(ex, "loading a Graph from")), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleHttpError(webEx, "loading a Graph from")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleError(ex, "loading a Graph from")), state); } }
/// <summary> /// Queries the store asynchronously /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> /// <param name="timeoutMilliseconds">Query timeout in milliseconds</param> public void Query(string sparqlQuery, AsyncStorageCallback callback, object state, long timeoutMilliseconds) { Graph g = new Graph(); SparqlResultSet results = new SparqlResultSet(); this.Query(new GraphHandler(g), new ResultSetHandler(results), sparqlQuery, (sender, args, st) => { if (results.ResultsType != SparqlResultsType.Unknown) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQuery, sparqlQuery, results, args.Error), state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQuery, sparqlQuery, g, args.Error), state); } }, state, timeoutMilliseconds); }
/// <summary> /// Updates a Graph in the Store asychronously. /// </summary> /// <param name="graphUri">URI of the Graph to update.</param> /// <param name="additions">Triples to be added.</param> /// <param name="removals">Triples to be removed.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, object state) { Uri u = (String.IsNullOrEmpty(graphUri) ? null : UriFactory.Create(graphUri)); UpdateGraph(u, additions, removals, callback, state); }
protected virtual void SaveGraphAsync(bool autoCommit, IGraph g, AsyncStorageCallback callback, object state) { try { Dictionary<string, string> queryParams = new Dictionary<string, string>(); HttpWebRequest request; string boundary = String.Format("----------{0:N}", Guid.NewGuid()); StringBuilder sb = new StringBuilder(); if (g.BaseUri != null) { SparqlParameterizedString construct = new SparqlParameterizedString(); construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }"; construct.SetUri("graph", g.BaseUri); queryParams.Add("query", construct.ToString()); request = this.CreateRequest("/sparql", MimeTypesHelper.Any, "PUT", queryParams); request.ContentType = MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First(); } else { request = this.CreateRequest("/sparql?updatePost", MimeTypesHelper.Any, "POST", queryParams); request.ContentType = MimeTypesHelper.FormMultipart + "; boundary=" + boundary; string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}", boundary, "add", MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First(), ""); sb.Append(postData); } //Save the Data as TriG to the Request Stream TripleStore store = new TripleStore(); store.Add(g); this._writer.Save(store, new System.IO.StringWriter(sb)); if (g.BaseUri == null) { string footer = "\r\n--" + boundary + "--\r\n"; sb.Append(footer); } request.BeginGetRequestStream(r => { try { //Save the Data as TriG to the Request Stream using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(r), new UTF8Encoding())) { writer.Write(sb.ToString()); writer.Close(); } Tools.HttpDebugRequest(request); request.BeginGetResponse(r2 => { try { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2)) { Tools.HttpDebugResponse(response); //If we get here then it was OK response.Close(); } //Commit Transaction only if in auto-commit mode (active transaction will be null) if (autoCommit) { this.Commit((sender, args, st) => { if (args.WasSuccessful) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g), state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, args.Error), state); } }, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g), state); } } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state); } }, state); } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state); } }, state); } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state); } }
/// <summary> /// Saves a Graph to the Store asynchronously. /// </summary> /// <param name="g">Graph to save.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void SaveGraph(IGraph g, AsyncStorageCallback callback, object state) { this.AsyncSaveGraph(g, callback, state); }
/// <summary> /// Updates a Graph in the Store asychronously. /// </summary> /// <param name="graphUri">URI of the Graph to update.</param> /// <param name="additions">Triples to be added.</param> /// <param name="removals">Triples to be removed.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void UpdateGraph(Uri graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, object state) { this.AsyncUpdateGraph(graphUri, additions, removals, callback, state); }
/// <summary> /// Loads a Graph from the Store asynchronously. /// </summary> /// <param name="handler">Handler to load with.</param> /// <param name="graphUri">URI of the Graph to load.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void LoadGraph(IRdfHandler handler, string graphUri, AsyncStorageCallback callback, object state) { Uri u = (String.IsNullOrEmpty(graphUri) ? null : UriFactory.Create(graphUri)); LoadGraph(handler, u, callback, state); }
/// <summary> /// Loads a Graph from the Store asynchronously. /// </summary> /// <param name="handler">Handler to load with.</param> /// <param name="graphUri">URI of the Graph to load.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void LoadGraph(IRdfHandler handler, Uri graphUri, AsyncStorageCallback callback, object state) { this.AsyncLoadGraph(handler, graphUri, callback, state); }
/// <summary> /// Loads a Graph from the Store asynchronously. /// </summary> /// <param name="g">Graph to load into.</param> /// <param name="graphUri">URI of the Graph to load.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void LoadGraph(IGraph g, Uri graphUri, AsyncStorageCallback callback, object state) { this.AsyncLoadGraph(g, graphUri, callback, state); }
/// <summary> /// Begins a transaction asynchronously /// </summary> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public virtual void Begin(AsyncStorageCallback callback, object state) { string tID; lock (transLock) { tID = this._activeTrans; } try { if (tID != null) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, new RdfStorageException("Cannot start a new Transaction as there is already an active Transaction")), state); } else { HttpWebRequest request = this.CreateRequest("/tx?timestamp=-1", "application/xml", "POST", new Dictionary<string, string>(), false); request.ContentType = MimeTypesHelper.WWWFormURLEncoded; try { Tools.HttpDebugRequest(request); request.BeginGetResponse(r => { try { string tResponse = null; using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r)) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { Tools.HttpDebugResponse(response); tResponse = reader.ReadToEnd(); reader.Close(); } response.Close(); } XmlDocument doc = new XmlDocument(); doc.LoadXml(tResponse); var node = doc.SelectSingleNode("/response/tx/@txId"); if (node != null) { tID = node.Value; } if (string.IsNullOrEmpty(tID)) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, new RdfStorageException("Blazegraph failed to begin a transaction")), state); } else { lock (transLock) { this._activeTrans = tID; } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin), state); } } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, StorageHelper.HandleHttpError(webEx, "beginning a Transaction in")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, StorageHelper.HandleError(ex, "beginning a Transaction in")), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, StorageHelper.HandleHttpError(webEx, "beginning a Transaction in")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, StorageHelper.HandleError(ex, "beginning a Transaction in")), state); } } } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, StorageHelper.HandleHttpError(webEx, "beginning a Transaction in")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionBegin, StorageHelper.HandleError(ex, "beginning a Transaction in")), state); } }
/// <summary> /// Deletes a Graph from the Store. /// </summary> /// <param name="graphUri">URI of the Graph to delete.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void DeleteGraph(Uri graphUri, AsyncStorageCallback callback, object state) { this.AsyncDeleteGraph(graphUri, callback, state); }
protected virtual void DeleteGraphAsync(bool autoCommit, string graphUri, AsyncStorageCallback callback, object state) { try { Uri graph = UriFactory.Create(graphUri); Dictionary<string, string> queryParams = new Dictionary<string, string>(); if (!graphUri.Equals(string.Empty)) { queryParams.Add("c", "<" + graph.ToSafeString() + ">"); } HttpWebRequest request = this.CreateRequest("/sparql", MimeTypesHelper.Any, "DELETE", queryParams); request.ContentType = MimeTypesHelper.WWWFormURLEncoded; Tools.HttpDebugRequest(request); request.BeginGetResponse(r => { try { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r)) { Tools.HttpDebugResponse(response); //If we get here then the Delete worked OK response.Close(); } //Commit Transaction only if in auto-commit mode (active transaction will be null) if (autoCommit) { this.Commit((sender, args, st) => { if (args.WasSuccessful) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri()), state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), args.Error), state); } }, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri()), state); } } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), StorageHelper.HandleHttpError(webEx, "deleting a Graph asynchronously from")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), StorageHelper.HandleError(ex, "deleting a Graph asynchronously from")), state); } }, state); } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), StorageHelper.HandleHttpError(webEx, "deleting a Graph asynchronously from")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), StorageHelper.HandleError(ex, "deleting a Graph asynchronously from")), state); } }
/// <summary> /// Deletes a Graph from the Store. /// </summary> /// <param name="graphUri">URI of the Graph to delete.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void DeleteGraph(string graphUri, AsyncStorageCallback callback, object state) { Uri u = (String.IsNullOrEmpty(graphUri) ? null : UriFactory.Create(graphUri)); DeleteGraph(u, callback, state); }
protected virtual void UpdateGraphAsync(bool autoCommit, string graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals, AsyncStorageCallback callback, object state) { try { Dictionary<string, string> queryParams = new Dictionary<string, string>(); HttpWebRequest request; string boundary = String.Format("----------{0:N}", Guid.NewGuid()); StringBuilder sb = new StringBuilder(); request = this.CreateRequest("/sparql?updatePost", MimeTypesHelper.Any, "POST", queryParams); request.ContentType = MimeTypesHelper.FormMultipart + "; boundary=" + boundary; string addData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}", boundary, "add", MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First(), ""); sb.Append(addData); //Save the Data as TriG to the Request Stream TripleStore store = new TripleStore(); Graph g = new Graph(); if (!string.IsNullOrEmpty(graphUri)) { g.BaseUri = UriFactory.Create(graphUri); } g.Assert(additions); store.Add(g); this._writer.Save(store, new System.IO.StringWriter(sb)); string removeData = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}", boundary, "remove", MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First(), ""); sb.Append(removeData); store = new TripleStore(); g = new Graph(); if (!string.IsNullOrEmpty(graphUri)) { g.BaseUri = UriFactory.Create(graphUri); } g.Assert(removals); store.Add(g); this._writer.Save(store, new System.IO.StringWriter(sb)); string footer = "\r\n--" + boundary + "--\r\n"; sb.Append(footer); request.BeginGetRequestStream(r => { try { //Save the Data as TriG to the Request Stream using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(r), new UTF8Encoding())) { writer.Write(sb.ToString()); writer.Close(); } Tools.HttpDebugRequest(request); request.BeginGetResponse(r2 => { try { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2)) { Tools.HttpDebugResponse(response); //If we get here then it was OK response.Close(); } //Commit Transaction only if in auto-commit mode (active transaction will be null) if (autoCommit) { this.Commit((sender, args, st) => { if (args.WasSuccessful) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), args.Error), state); } }, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); } } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state); } }, state); } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state); } }, state); } catch (WebException webEx) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state); } catch (Exception ex) { if (autoCommit) { //If something went wrong try to rollback, don't care what the rollback response is this.Rollback((sender, args, st) => { }, state); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state); } }
/// <summary> /// Lists the Graphs in the Store asynchronously. /// </summary> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public void ListGraphs(AsyncStorageCallback callback, object state) { this.AsyncListGraphs(callback, state); }
/// <summary> /// Queries the store asynchronously /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public virtual void Query(string sparqlQuery, AsyncStorageCallback callback, object state) { this.Query(sparqlQuery, callback, state, -1); }
/// <summary> /// Executes a SPARQL Query on the Fuseki store processing the results using an appropriate handler from those provided /// </summary> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> /// <returns></returns> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery, AsyncStorageCallback callback, Object state) { try { HttpWebRequest request; //Create the Request, always use POST for async for simplicity String queryUri = this._queryUri; request = (HttpWebRequest)WebRequest.Create(queryUri); request.Method = "POST"; request.Accept = MimeTypesHelper.HttpRdfOrSparqlAcceptHeader; request = base.ApplyRequestOptions(request); //Build the Post Data and add to the Request Body request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded; StringBuilder postData = new StringBuilder(); postData.Append("query="); postData.Append(HttpUtility.UrlEncode(sparqlQuery)); request.BeginGetRequestStream(r => { try { Stream stream = request.EndGetRequestStream(r); using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8))) { writer.Write(postData); writer.Close(); } Tools.HttpDebugRequest(request); //Get the Response and process based on the Content Type request.BeginGetResponse(r2 => { try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2); Tools.HttpDebugResponse(response); StreamReader data = new StreamReader(response.GetResponseStream()); String ctype = response.ContentType; try { //Is the Content Type referring to a Sparql Result Set format? ISparqlResultsReader resreader = MimeTypesHelper.GetSparqlParser(ctype, true); resreader.Load(resultsHandler, data); response.Close(); } catch (RdfParserSelectionException) { //If we get a Parse exception then the Content Type isn't valid for a Sparql Result Set //Is the Content Type referring to a RDF format? IRdfReader rdfreader = MimeTypesHelper.GetParser(ctype); rdfreader.Load(rdfHandler, data); response.Close(); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, sparqlQuery, rdfHandler, resultsHandler), state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }
/// <summary> /// Loads a Graph from the Store asynchronously. /// </summary> /// <param name="handler">Handler to load with.</param> /// <param name="graphUri">URI of the Graph to load.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public virtual void LoadGraph(IRdfHandler handler, Uri graphUri, AsyncStorageCallback callback, object state) { LoadGraph(handler, graphUri.ToSafeString(), callback, state); }
/// <summary> /// Updates a Graph on the Fuseki Server /// </summary> /// <param name="graphUri">URI of the Graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, object state) { try { String graph = (graphUri != null && !graphUri.Equals(String.Empty)) ? "GRAPH <" + this._formatter.FormatUri(graphUri) + "> {" : String.Empty; StringBuilder update = new StringBuilder(); if (additions != null) { if (additions.Any()) { update.AppendLine("INSERT DATA {"); if (!graph.Equals(String.Empty)) { update.AppendLine(graph); } foreach (Triple t in additions) { update.AppendLine(this._formatter.Format(t)); } if (!graph.Equals(String.Empty)) { update.AppendLine("}"); } update.AppendLine("}"); } } if (removals != null) { if (removals.Any()) { if (update.Length > 0) { update.AppendLine(";"); } update.AppendLine("DELETE DATA {"); if (!graph.Equals(String.Empty)) { update.AppendLine(graph); } foreach (Triple t in removals) { update.AppendLine(this._formatter.Format(t)); } if (!graph.Equals(String.Empty)) { update.AppendLine("}"); } update.AppendLine("}"); } } if (update.Length > 0) { this.Update(update.ToString(), (sender, args, st) => { if (args.WasSuccessful) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), args.Error), state); } }, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); } } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously")), state); } }
/// <summary> /// Gets a default template for creating a store. /// </summary> /// <param name="id">Store ID.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> /// <returns></returns> public virtual void GetDefaultTemplate(string id, AsyncStorageCallback callback, object state) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.NewTemplate, id, new SesameMemTemplate(id)), state); }
/// <summary> /// Updates a Graph in the Store asychronously /// </summary> /// <param name="graphUri">URI of the Graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, object state) { if (!this._updatesEnabled) { throw new RdfStorageException("4store does not support Triple level updates"); } else if (graphUri.Equals(String.Empty)) { throw new RdfStorageException("Cannot update a Graph without a Graph URI on a 4store Server"); } else { try { StringBuilder delete = new StringBuilder(); if (removals != null) { if (removals.Any()) { //Build up the DELETE command and execute delete.AppendLine("DELETE DATA"); delete.AppendLine("{ GRAPH <" + graphUri.Replace(">", "\\>") + "> {"); foreach (Triple t in removals) { delete.AppendLine(t.ToString(this._formatter)); } delete.AppendLine("}}"); } } StringBuilder insert = new StringBuilder(); if (additions != null) { if (additions.Any()) { //Build up the INSERT command and execute insert.AppendLine("INSERT DATA"); insert.AppendLine("{ GRAPH <" + graphUri.Replace(">", "\\>") + "> {"); foreach (Triple t in additions) { insert.AppendLine(t.ToString(this._formatter)); } insert.AppendLine("}}"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this._baseUri + "update/"); request.Method = "POST"; request.ContentType = MimeTypesHelper.WWWFormURLEncoded; request = base.GetProxiedRequest(request); } } //Use Update() method to send the updates if (delete.Length > 0) { if (insert.Length > 0) { this.Update(delete.ToString() + "\n;\n" + insert.ToString(), (sender, args, st) => { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), args.Error), state); }, state); } else { this.Update(delete.ToString(), (sender, args, st) => { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), args.Error), state); }, state); } } else if (insert.Length > 0) { this.Update(insert.ToString(), (sender, args, st) => { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), args.Error), state); }, state); } else { //Nothing to do callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); } } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state); } } }
/// <summary> /// Queries the store asynchronously /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery, AsyncStorageCallback callback, object state) { this.AsyncQueryHandlers(sparqlQuery, rdfHandler, resultsHandler, callback, state); }
/// <summary> /// Updates a Graph on the Protocol Server /// </summary> /// <param name="graphUri">URI of the Graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> /// <remarks> /// <strong>Note:</strong> The SPARQL Graph Store HTTP Protocol for Graph Management only supports the addition of Triples to a Graph and does not support removal of Triples from a Graph. If you attempt to remove Triples then an <see cref="RdfStorageException">RdfStorageException</see> will be thrown /// </remarks> public override void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, Object state) { if (removals != null && removals.Any()) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), new RdfStorageException("Unable to Update a Graph since this update requests that Triples be removed from the Graph which the SPARQL Graph Store HTTP Protocol for Graph Management does not support")), state); return; } if (additions == null || !additions.Any()) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); return; } String updateUri = this._serviceUri; if (graphUri != null && !graphUri.Equals(String.Empty)) { updateUri += "?graph=" + HttpUtility.UrlEncode(graphUri); } else { updateUri += "?default"; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UriFactory.Create(updateUri)); request.Method = "POST"; request.ContentType = MimeTypesHelper.RdfXml[0]; request = base.GetProxiedRequest(request); RdfXmlWriter writer = new RdfXmlWriter(); this.UpdateGraphAsync(request, writer, graphUri.ToSafeUri(), additions, callback, state); }
/// <summary> /// Gets a default template for creating a new Store /// </summary> /// <param name="id">Store ID</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to callback</param> /// <returns></returns> public override void GetDefaultTemplate(string id, AsyncStorageCallback callback, object state) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.NewTemplate, id, new StoreTemplate(id)), state); }
/// <summary> /// Lists the Graphs in the Store asynchronously /// </summary> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void ListGraphs(AsyncStorageCallback callback, Object state) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListGraphs, new NotSupportedException("SPARQL HTTP Protocol Connector does not support listing graphs")), state); }
/// <summary> /// Saves a Graph to the Store asynchronously /// </summary> /// <param name="g">Graph to save</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void SaveGraph(IGraph g, AsyncStorageCallback callback, object state) { this.SaveGraphAsync(g, callback, state); }
/// <summary> /// Updates a Graph asynchronously. /// </summary> /// <param name="storage">Storage Provider.</param> /// <param name="graphUri">URI of the Graph to update.</param> /// <param name="additions">Triples to add.</param> /// <param name="removals">Triples to remove.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> internal static void AsyncUpdateGraph(this IStorageProvider storage, Uri graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, object state) { Task.Factory.StartNew(() => UpdateGraph(storage, graphUri, additions, removals)).ContinueWith(antecedent => callback(storage, antecedent.IsFaulted ? new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, antecedent.Exception) : new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri), state)); }
/// <summary> /// Updates a Graph in the Store asychronously /// </summary> /// <param name="graphUri">URI of the Graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void UpdateGraph(string graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals, AsyncStorageCallback callback, object state) { //If there are no adds or deletes, just callback and avoid creating empty transaction bool anyData = false; if (removals != null && removals.Any()) anyData = true; if (additions != null && additions.Any()) anyData = true; if (!anyData) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); } else { this.UpdateGraphAsync(graphUri, additions, removals, callback, state); } }
/// <summary> /// Deletes a Graph asynchronously. /// </summary> /// <param name="storage">Storage Provider.</param> /// <param name="graphUri">URI of the Graph to delete.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> internal static void AsyncDeleteGraph(this IStorageProvider storage, Uri graphUri, AsyncStorageCallback callback, object state) { Task.Factory.StartNew(() => DeleteGraph(storage, graphUri)).ContinueWith(antecedent => callback(storage, antecedent.IsFaulted ? new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri, antecedent.Exception) : new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri), state)); }
protected virtual void SaveGraphAsync(IGraph g, AsyncStorageCallback callback, object state) { //Get a Transaction ID, if there is no active Transaction then this operation will start a new transaction and be auto-committed string activeTID; lock (transLock) { activeTID = this._activeTrans; } if (activeTID != null) { this.SaveGraphAsync(false, g, callback, state); } else { this.Begin((sender, args, st) => { if (args.WasSuccessful) { this.SaveGraphAsync(true, g, callback, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, args.Error), state); } }, state); } }
/// <summary> /// Queries a store asynchronously. /// </summary> /// <param name="storage">Storage Provider.</param> /// <param name="query">SPARQL Query.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> internal static void AsyncQuery(this IQueryableStorage storage, string query, AsyncStorageCallback callback, object state) { Task.Factory.StartNew(() => Query(storage, query)).ContinueWith(antecedent => callback(storage, antecedent.IsFaulted ? new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQuery, query, antecedent.Exception) : new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQuery, query, antecedent.Result), state)); }
protected virtual void UpdateGraphAsync(string graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals, AsyncStorageCallback callback, object state) { //Get a Transaction ID, if there is no active Transaction then this operation will start a new transaction and be auto-committed string activeTID; lock (transLock) { activeTID = this._activeTrans; } if (activeTID != null) { this.UpdateGraphAsync(false, graphUri, additions, removals, callback, state); } else { this.Begin((sender, args, st) => { if (args.WasSuccessful) { this.UpdateGraphAsync(true, graphUri, additions, removals, callback, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), args.Error), state); } }, state); } }
/// <summary> /// Queries a store asynchronously. /// </summary> /// <param name="storage">Storage Provider.</param> /// <param name="query">SPARQL Query.</param> /// <param name="rdfHandler">RDF Handler.</param> /// <param name="resultsHandler">Results Handler.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> internal static void AsyncQueryHandlers(this IQueryableStorage storage, string query, IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, AsyncStorageCallback callback, object state) { Task.Factory.StartNew(() => QueryHandlers(storage, query, rdfHandler, resultsHandler)).ContinueWith( antecedent => callback(storage, antecedent.IsFaulted ? new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, query, rdfHandler, resultsHandler, antecedent.Exception) : new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, query, rdfHandler, resultsHandler), state)); }
/// <summary> /// Deletes a Graph from the Store /// </summary> /// <param name="graphUri">URI of the Graph to delete</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void DeleteGraph(string graphUri, AsyncStorageCallback callback, object state) { //Get a Transaction ID, if there is no active Transaction then this operation will start a new transaction and be auto-committed string activeTID; lock (transLock) { activeTID = this._activeTrans; } if (activeTID != null) { this.DeleteGraphAsync(false, graphUri, callback, state); } else { this.Begin((sender, args, st) => { if (args.WasSuccessful) { this.DeleteGraphAsync(true, graphUri, callback, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), args.Error), state); } }, state); } }
/// <summary> /// Updates a store asynchronously. /// </summary> /// <param name="storage">Storage Provider.</param> /// <param name="updates">SPARQL Update.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> internal static void AsyncUpdate(this IUpdateableStorage storage, string updates, AsyncStorageCallback callback, object state) { Task.Factory.StartNew(() => Update(storage, updates)).ContinueWith(antecedent => callback(storage, antecedent.IsFaulted ? new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, updates, antecedent.Exception) : new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, updates), state)); }
/// <summary> /// Queries the store asynchronously /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public virtual void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery, AsyncStorageCallback callback, object state) { this.Query(rdfHandler, resultsHandler, sparqlQuery, callback, state, -1); }
/// <summary> /// Loads a Graph asynchronously. /// </summary> /// <param name="storage">Storage Provider.</param> /// <param name="handler">Handler to load with.</param> /// <param name="graphUri">URI of the Graph to load.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> internal static void AsyncLoadGraph(this IStorageProvider storage, IRdfHandler handler, Uri graphUri, AsyncStorageCallback callback, object state) { Task.Factory.StartNew(() => LoadGraph(storage, handler, graphUri)).ContinueWith(antecedent => callback(storage, antecedent.IsFaulted ? new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler, antecedent.Exception) : new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler), state)); }
/// <summary> /// Queries the store asynchronously /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> /// <param name="timeoutMilliseconds">Query timeout in milliseconds</param> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery, AsyncStorageCallback callback, object state, long timeoutMilliseconds) { try { HttpWebRequest request; string accept = MimeTypesHelper.HttpRdfOrSparqlAcceptHeader; Dictionary<string, string> queryParams = new Dictionary<string, string>(); request = this.CreateRequest("/sparql", accept, "POST", queryParams); if (timeoutMilliseconds != -1) { request.Headers[BlazeGraphQueryTimeoutHeader] = timeoutMilliseconds.ToString(); } request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded; request.BeginGetRequestStream(r => { try { Stream stream = request.EndGetRequestStream(r); using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8))) { writer.Write("query="); writer.Write(HttpUtility.UrlEncode(sparqlQuery)); string tID; lock (transLock) { tID = this._activeTrans; } if (tID != null) { writer.Write("×tamp=" + tID); } writer.Close(); } Tools.HttpDebugRequest(request); //Get the Response and process based on the Content Type request.BeginGetResponse(r2 => { try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2); Tools.HttpDebugResponse(response); StreamReader data = new StreamReader(response.GetResponseStream()); string ctype = response.ContentType; try { //Is the Content Type referring to a Sparql Result Set format? ISparqlResultsReader resreader = MimeTypesHelper.GetSparqlParser(ctype, Regex.IsMatch(sparqlQuery, "ASK", RegexOptions.IgnoreCase)); resreader.Load(resultsHandler, data); response.Close(); } catch (RdfParserSelectionException) { //If we get a Parser Selection exception then the Content Type isn't valid for a Sparql Result Set //Is the Content Type referring to a RDF format? IRdfReader rdfreader = MimeTypesHelper.GetParser(ctype); rdfreader.Load(rdfHandler, data); response.Close(); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, sparqlQuery, rdfHandler, resultsHandler), state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpQueryError(webEx)), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleQueryError(ex)), state); } }
/// <summary> /// Updates an existing Graph in the Store by adding and removing triples /// </summary> /// <param name="graphUri">URI of the graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> /// <remarks> /// Removals are processed before any additions, to force a specific order of additions and removals you should make multiple calls to this function specifying each set of additions or removals you wish to perform seperately /// </remarks> public override void UpdateGraph(String graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, Object state) { StringBuilder sparqlUpdate = new StringBuilder(); //Build the SPARQL Update Commands if (removals != null && removals.Any()) { sparqlUpdate.AppendLine("DELETE DATA"); sparqlUpdate.AppendLine("{"); if (graphUri != null && !graphUri.Equals(String.Empty)) { sparqlUpdate.AppendLine("GRAPH <" + this._formatter.FormatUri(graphUri) + "> {"); } foreach (Triple t in removals) { sparqlUpdate.AppendLine(t.ToString(this._formatter)); } if (graphUri != null && !graphUri.Equals(String.Empty)) { sparqlUpdate.AppendLine("}"); } sparqlUpdate.AppendLine("}"); } if (additions != null && additions.Any()) { sparqlUpdate.AppendLine("INSERT DATA"); sparqlUpdate.AppendLine("{"); if (graphUri != null && !graphUri.Equals(String.Empty)) { sparqlUpdate.AppendLine("GRAPH <" + this._formatter.FormatUri(graphUri) + "> {"); } foreach (Triple t in additions) { sparqlUpdate.AppendLine(t.ToString(this._formatter)); } if (graphUri != null && !graphUri.Equals(String.Empty)) { sparqlUpdate.AppendLine("}"); } sparqlUpdate.AppendLine("}"); } //Send them to Dydra for processing if (sparqlUpdate.Length > 0) { this.Update(sparqlUpdate.ToString(), (sender, args, st) => { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), args.Error), state); }, state); } }
/// <summary> /// Rolls back a transaction asynchronously /// </summary> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public virtual void Rollback(AsyncStorageCallback callback, object state) { string tID; lock (transLock) { tID = this._activeTrans; } try { if (tID == null) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback, new RdfStorageException("Cannot rollback a Transaction on the as there is currently no active Transaction")), state); } else { HttpWebRequest request = this.CreateRequest("/tx/" + tID + "?ABORT", "application/xml", "POST", new Dictionary<string, string>(), false); request.ContentType = MimeTypesHelper.WWWFormURLEncoded; try { request.BeginGetResponse(r => { try { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r)) { response.Close(); } lock (transLock) { if (this._activeTrans != null && this._activeTrans.Equals(tID)) { this._activeTrans = null; } } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback), state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback, StorageHelper.HandleHttpError(webEx, "rolling back a Transaction from")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback, StorageHelper.HandleError(ex, "rolling back a Transaction from")), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback, StorageHelper.HandleHttpError(webEx, "rolling back a Transaction from")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback, StorageHelper.HandleError(ex, "rolling back a Transaction from")), state); } } } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback, StorageHelper.HandleHttpError(webEx, "rolling back a Transaction from")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.TransactionRollback, StorageHelper.HandleError(ex, "rolling back a Transaction from")), state); } }
/// <summary> /// Loads a Graph from the Store asynchronously. /// </summary> /// <param name="g">Graph to load into.</param> /// <param name="graphUri">URI of the Graph to load.</param> /// <param name="callback">Callback.</param> /// <param name="state">State to pass to the callback.</param> public virtual void LoadGraph(IGraph g, string graphUri, AsyncStorageCallback callback, object state) { LoadGraph(new GraphHandler(g), graphUri, (sender, args, st) => callback(sender, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadGraph, g, args.Error), st), state); }