/// <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 = _queryUri;

                request        = (HttpWebRequest)WebRequest.Create(queryUri);
                request.Method = "POST";
                request.Accept = MimeTypesHelper.HttpRdfOrSparqlAcceptHeader;
                request        = 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>
        /// Executes SPARQL Updates against the Fuseki store.
        /// </summary>
        /// <param name="sparqlUpdate">SPARQL Update.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="state">State to pass to the callback.</param>
        public void Update(String sparqlUpdate, AsyncStorageCallback callback, Object state)
        {
            try
            {
                // Make the SPARQL Update Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_updateUri);
                request.Method      = "POST";
                request.ContentType = "application/sparql-update";
                request             = ApplyRequestOptions(request);

                request.BeginGetRequestStream(r =>
                {
                    try
                    {
                        Stream stream       = request.EndGetRequestStream(r);
                        StreamWriter writer = new StreamWriter(stream);
                        writer.Write(sparqlUpdate);
                        writer.Close();

                        Tools.HttpDebugRequest(request);

                        request.BeginGetResponse(r2 =>
                        {
                            try
                            {
                                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                                Tools.HttpDebugResponse(response);
                                // If we get here without erroring then the request was OK
                                response.Close();
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate), state);
                            }
                            catch (WebException webEx)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleHttpError(webEx, "updating")), state);
                            }
                            catch (Exception ex)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleError(ex, "updating")), state);
                            }
                        }, state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleHttpError(webEx, "updating")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleError(ex, "updating")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleHttpError(webEx, "updating")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleError(ex, "updating")), state);
            }
        }
        /// <summary>
        /// Updates a Graph in the Fuseki store.
        /// </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>
        public override void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals)
        {
            try
            {
                String        graph  = (graphUri != null && !graphUri.Equals(String.Empty)) ? "GRAPH <" + _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(_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(_formatter.Format(t));
                        }

                        if (!graph.Equals(String.Empty))
                        {
                            update.AppendLine("}");
                        }
                        update.AppendLine("}");
                    }
                }

                if (update.Length > 0)
                {
                    // Make the SPARQL Update Request
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_updateUri);
                    request.Method      = "POST";
                    request.ContentType = "application/sparql-update";
                    request             = ApplyRequestOptions(request);

                    Tools.HttpDebugRequest(request);

                    StreamWriter writer = new StreamWriter(request.GetRequestStream());
                    writer.Write(update.ToString());
                    writer.Close();

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        Tools.HttpDebugResponse(response);

                        // If we get here without erroring then the request was OK
                        response.Close();
                    }
                }
            }
            catch (WebException webEx)
            {
                throw StorageHelper.HandleHttpError(webEx, "updating a Graph in");
            }
        }
        /// <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>
        /// <returns></returns>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
        {
            try
            {
                HttpWebRequest request;

                // Create the Request
                String queryUri = _queryUri;
                if (sparqlQuery.Length < 2048)
                {
                    queryUri      += "?query=" + Uri.EscapeDataString(sparqlQuery);
                    request        = (HttpWebRequest)WebRequest.Create(queryUri);
                    request.Method = "GET";
                    request.Accept = MimeTypesHelper.HttpRdfOrSparqlAcceptHeader;
                    request        = ApplyRequestOptions(request);
                }
                else
                {
                    request        = (HttpWebRequest)WebRequest.Create(queryUri);
                    request.Method = "POST";
                    request.Accept = MimeTypesHelper.HttpRdfOrSparqlAcceptHeader;
                    request        = 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));
                    using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), new UTF8Encoding(Options.UseBomForUtf8)))
                    {
                        writer.Write(postData);
                        writer.Close();
                    }
                }

                Tools.HttpDebugRequest(request);

                // Get the Response and process based on the Content Type
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Tools.HttpDebugResponse(response);

                    StreamReader data  = new StreamReader(response.GetResponseStream());
                    String       ctype = response.ContentType;
                    try
                    {
                        // Is the Content Type referring to a RDF format?
                        IRdfReader rdfreader = MimeTypesHelper.GetParser(ctype);
                        rdfreader.Load(rdfHandler, data);
                        response.Close();
                    }
                    catch (RdfParserSelectionException)
                    {
                        // If we get a Parser selection exception then the Content Type isn't valid for a RDF Graph

                        // Is the Content Type referring to a Sparql Result Set format?
                        ISparqlResultsReader resreader = MimeTypesHelper.GetSparqlParser(ctype, true);
                        resreader.Load(resultsHandler, data);
                        response.Close();
                    }
                }
            }
            catch (WebException webEx)
            {
                throw StorageHelper.HandleHttpQueryError(webEx);
            }
        }
Example #5
0
        /// <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)
        {
            try
            {
                HttpWebRequest request = this.CreateRequest("/sparql", MimeTypesHelper.HttpSparqlAcceptHeader, "POST", null);
                request.BeginGetRequestStream(r =>
                {
                    try
                    {
                        Stream stream = request.EndGetRequestStream(r);
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write("query=");
                            writer.Write(HttpUtility.UrlEncode(sparqlUpdates));
                            writer.Close();
                        }
                        Tools.HttpDebugRequest(request);

                        request.BeginGetResponse(r2 =>
                        {
                            try
                            {
                                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                                Tools.HttpDebugResponse(response);
                                //If we get here then it completed OK
                                response.Close();
                            }
                            catch (WebException webEx)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpError(webEx, "updating")), state);
                            }
                            catch (Exception ex)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleError(ex, "updating")), state);
                            }
                        }, state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpError(webEx, "updating")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleError(ex, "updating")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleHttpError(webEx, "updating")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlQueryWithHandler, StorageHelper.HandleError(ex, "updating")), state);
            }
        }
        /// <summary>
        /// Makes a SPARQL Update request to the Allegro Graph server
        /// </summary>
        /// <param name="sparqlUpdate">SPARQL Update</param>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        public virtual void Update(string sparqlUpdate, AsyncStorageCallback callback, Object state)
        {
            try
            {
                HttpWebRequest request;

                // Create the Request
                request = CreateRequest(_repositoriesPrefix + _store + _updatePath, MimeTypesHelper.Any, "POST", new Dictionary <String, String>());

                // 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(EscapeQuery(sparqlUpdate)));

                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);
                                // If we get here it completed OK
                                response.Close();
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate), state);
                            }
                            catch (WebException webEx)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleHttpError(webEx, "updating")), state);
                            }
                            catch (Exception ex)
                            {
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleError(ex, "updating")), state);
                            }
                        }, state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleHttpError(webEx, "updating")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleError(ex, "updating")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleHttpError(webEx, "updating")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SparqlUpdate, sparqlUpdate, StorageHelper.HandleError(ex, "updating")), state);
            }
        }
Example #7
0
        /// <summary>
        /// Lists the Graphs from the Repository
        /// </summary>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        /// <returns></returns>
        public override void ListGraphs(AsyncStorageCallback callback, Object state)
        {
            try
            {
                //Use the /contexts method to get the Graph URIs
                //HACK: Have to use SPARQL JSON as currently Dydra's SPARQL XML Results are malformed
                HttpWebRequest request = this.CreateRequest("/contexts", MimeTypesHelper.CustomHttpAcceptHeader(MimeTypesHelper.SparqlResultsJson), "GET", new Dictionary <string, string>());
                request.BeginGetResponse(r =>
                {
                    try
                    {
                        HttpWebResponse response    = (HttpWebResponse)request.EndGetResponse(r);
                        ISparqlResultsReader parser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                        ListUrisHandler handler     = new ListUrisHandler("contextID");
                        parser.Load(handler, new StreamReader(response.GetResponseStream()));
                        response.Close();

                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListGraphs, handler.Uris), state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListGraphs, StorageHelper.HandleHttpError(webEx, "list Graphs asynchronously from")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListGraphs, StorageHelper.HandleError(ex, "list Graphs asynchronously from")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListGraphs, StorageHelper.HandleHttpError(webEx, "list Graphs asynchronously from")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.ListGraphs, StorageHelper.HandleError(ex, "list Graphs asynchronously from")), state);
            }
        }
Example #8
0
        /// <summary>
        /// Helper method for doing async load operations, callers just need to provide an appropriately prepared HTTP request.
        /// </summary>
        /// <param name="request">HTTP Request.</param>
        /// <param name="handler">Handler to load with.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="state">State to pass to the callback.</param>
        protected internal void LoadGraphAsync(HttpWebRequest request, IRdfHandler handler, AsyncStorageCallback callback, object state)
        {
            Tools.HttpDebugRequest(request);
            request.BeginGetResponse(r =>
            {
                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r);
                    Tools.HttpDebugResponse(response);
                    // Parse the retrieved RDF
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));

                    // If we get here then it was OK
                    response.Close();

                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler), state);
                }
                catch (WebException webEx)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        if (((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.NotFound)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler), state);
                            return;
                        }
                    }
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler, new RdfStorageException("A HTTP Error occurred while trying to load a Graph from the Store", webEx)), state);
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler, StorageHelper.HandleError(ex, "loading a Graph asynchronously from")), state);
                }
            }, 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);
                }
            }
        }
Example #10
0
        /// <summary>
        /// Performs a SPARQL Query against the underlying Store
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">SPARQL Results Handler</param>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <returns></returns>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery)
        {
            try
            {
                //First off parse the Query to see what kind of query it is
                SparqlQuery q;
                try
                {
                    q = this._parser.ParseFromString(sparqlQuery);
                }
                catch (RdfParseException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw 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);
                }

                //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
                HttpWebRequest request;
                Dictionary <String, String> queryParams = new Dictionary <string, string>();
                if (sparqlQuery.Length < 2048)
                {
                    queryParams.Add("query", sparqlQuery);

                    request = this.CreateRequest("/sparql", accept, "GET", queryParams);
                }
                else
                {
                    request = this.CreateRequest("/sparql", accept, "POST", queryParams);

                    //Build the Post Data and add to the Request Body
                    request.ContentType = MimeTypesHelper.WWWFormURLEncoded;
                    StringBuilder postData = new StringBuilder();
                    postData.Append("query=");
                    postData.Append(HttpUtility.UrlEncode(sparqlQuery));
                    StreamWriter writer = new StreamWriter(request.GetRequestStream());
                    writer.Write(postData);
                    writer.Close();
                }

                Tools.HttpDebugRequest(request);

                //Get the Response and process based on the Content Type
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    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)
            {
                throw StorageHelper.HandleHttpQueryError(webEx);
            }
        }
Example #11
0
        /// <summary>
        /// Helper method for doing async delete operations, callers just need to provide an appropriately prepared HTTP request.
        /// </summary>
        /// <param name="request">HTTP request.</param>
        /// <param name="allow404">Whether a 404 response counts as success.</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>
        protected internal void DeleteGraphAsync(HttpWebRequest request, bool allow404, string graphUri, AsyncStorageCallback callback, object state)
        {
            Tools.HttpDebugRequest(request);
            request.BeginGetResponse(r =>
            {
                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r);

                    // Assume if returns to here we deleted the Graph OK
                    response.Close();
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri()), state);
                }
                catch (WebException webEx)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                    // Don't throw the error if we get a 404 - this means we couldn't do a delete as the graph didn't exist to start with
                    if (webEx.Response == null || (webEx.Response != null && (!allow404 || ((HttpWebResponse)webEx.Response).StatusCode != HttpStatusCode.NotFound)))
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), new RdfStorageException("A HTTP Error occurred while trying to delete a Graph from the Store asynchronously", webEx)), state);
                    }
                    else
                    {
                        // Consider a 404 as a success in some cases
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri()), state);
                    }
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), StorageHelper.HandleError(ex, "deleting a Graph asynchronously from")), state);
                }
            }, state);
        }
Example #12
0
        /// <summary>
        /// Helper method for doing async update operations, callers just need to provide an appropriately prepared HTTP request and a RDF writer which will be used to write the data to the request body.
        /// </summary>
        /// <param name="request">HTTP Request.</param>
        /// <param name="writer">RDF writer.</param>
        /// <param name="graphUri">URI of the Graph to update.</param>
        /// <param name="ts">Triples.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="state">State to pass to the callback.</param>
        protected internal void UpdateGraphAsync(HttpWebRequest request, IRdfWriter writer, Uri graphUri, IEnumerable <Triple> ts, AsyncStorageCallback callback, object state)
        {
            Graph g = new Graph();

            g.Assert(ts);

            request.BeginGetRequestStream(r =>
            {
                try
                {
                    Stream reqStream = request.EndGetRequestStream(r);
                    writer.Save(g, new StreamWriter(reqStream));

                    Tools.HttpDebugRequest(request);

                    request.BeginGetResponse(r2 =>
                    {
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                            Tools.HttpDebugResponse(response);
                            // If we get here then it was OK
                            response.Close();
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri), state);
                        }
                        catch (WebException webEx)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state);
                        }
                        catch (Exception ex)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state);
                        }
                    }, state);
                }
                catch (WebException webEx)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state);
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state);
                }
            }, state);
        }
Example #13
0
        /// <summary>
        /// Helper method for doing async save operations, callers just need to provide an appropriately perpared HTTP requests and a RDF writer which will be used to write the data to the request body.
        /// </summary>
        /// <param name="request">HTTP request.</param>
        /// <param name="writer">RDF Writer.</param>
        /// <param name="g">Graph to save.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="state">State to pass to the callback.</param>
        protected internal void SaveGraphAsync(HttpWebRequest request, IRdfWriter writer, IGraph g, AsyncStorageCallback callback, object state)
        {
            request.BeginGetRequestStream(r =>
            {
                try
                {
                    Stream reqStream = request.EndGetRequestStream(r);
                    writer.Save(g, new StreamWriter(reqStream));

                    Tools.HttpDebugRequest(request);

                    request.BeginGetResponse(r2 =>
                    {
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                            Tools.HttpDebugResponse(response);
                            // If we get here then it was OK
                            response.Close();
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g), state);
                        }
                        catch (WebException webEx)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state);
                        }
                        catch (Exception ex)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state);
                        }
                    }, state);
                }
                catch (WebException webEx)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state);
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state);
                }
            }, 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 <" + _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(_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(_formatter.Format(t));
                        }

                        if (!graph.Equals(String.Empty))
                        {
                            update.AppendLine("}");
                        }
                        update.AppendLine("}");
                    }
                }

                if (update.Length > 0)
                {
                    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);
            }
        }
Example #15
0
        /// <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>
        /// Deletes a Graph from the store asynchronously.
        /// </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)
        {
            String deleteUri = _serviceUri;

            if (graphUri != null && !graphUri.Equals(String.Empty))
            {
                deleteUri += "?graph=" + Uri.EscapeDataString(graphUri);
            }
            else
            {
                deleteUri += "?default";
            }

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UriFactory.Create(deleteUri));
                request.Method = "DELETE";
                request        = ApplyRequestOptions(request);

                DeleteGraphAsync(request, true, graphUri, callback, state);
            }
            catch (WebException webEx)
            {
                // Don't throw the error if we get a 404 - this means we couldn't do a delete as the graph didn't exist to start with
                if (webEx.Response == null || (webEx.Response != null && ((HttpWebResponse)webEx.Response).StatusCode != HttpStatusCode.NotFound))
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri(), StorageHelper.HandleHttpError(webEx, "deleting a Graph from")), state);
                }
                else
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.DeleteGraph, graphUri.ToSafeUri()), state);
                }
            }
        }
Example #17
0
        /// <summary>
        /// Updates a Graph in the store.
        /// </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>
        /// <remarks>
        /// May throw an error since the default builds of 4store don't support Triple level updates.  There are builds that do support this and the user can instantiate the connector with support for this enabled if they wish, if they do so and the underlying 4store doesn't support updates errors will occur when updates are attempted.
        /// </remarks>
        public void UpdateGraph(String graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals)
        {
            if (!_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(_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(_formatter));
                            }
                            insert.AppendLine("}}");
                        }
                    }

                    // Use Update() method to send the updates
                    if (delete.Length > 0)
                    {
                        if (insert.Length > 0)
                        {
                            Update(delete.ToString() + "\n;\n" + insert.ToString());
                        }
                        else
                        {
                            Update(delete.ToString());
                        }
                    }
                    else if (insert.Length > 0)
                    {
                        Update(insert.ToString());
                    }
                }
                catch (WebException webEx)
                {
                    throw StorageHelper.HandleHttpError(webEx, "updating a Graph in");
                }
            }
        }