Ejemplo n.º 1
0
        /// <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 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);
            }
        }
Ejemplo n.º 3
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);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is a <see cref="SparqlResultSet">SparqlResultSet</see> i.e. SELECT and ASK Queries.
        /// </summary>
        /// <param name="query">SPARQL Query String.</param>
        /// <param name="handler">Results Handler.</param>
        /// <param name="callback">Callback to invoke when the query completes.</param>
        /// <param name="state">State to pass to the callback.</param>
        public void QueryWithResultSet(ISparqlResultsHandler handler, String query, QueryCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded;
            request.Accept      = RdfAcceptHeader;
            ApplyRequestOptions(request);
            Tools.HttpDebugRequest(request);

            try
            {
                request.BeginGetRequestStream(result =>
                {
                    try
                    {
                        Stream stream = request.EndGetRequestStream(result);
                        using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8)))
                        {
                            writer.Write("query=");
                            writer.Write(HttpUtility.UrlEncode(query));

                            foreach (String u in DefaultGraphs)
                            {
                                writer.Write("&default-graph-uri=");
                                writer.Write(HttpUtility.UrlEncode(u));
                            }
                            foreach (String u in NamedGraphs)
                            {
                                writer.Write("&named-graph-uri=");
                                writer.Write(HttpUtility.UrlEncode(u));
                            }

                            writer.Close();
                        }

                        request.BeginGetResponse(innerResult =>
                        {
                            try
                            {
                                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult))
                                {
                                    Tools.HttpDebugResponse(response);
                                    ISparqlResultsReader parser = MimeTypesHelper.GetSparqlParser(response.ContentType, false);
                                    parser.Load(handler, new StreamReader(response.GetResponseStream()));

                                    response.Close();
                                    callback(null, handler, state);
                                }
                            }
                            catch (SecurityException secEx)
                            {
                                callback(null, handler, new AsyncError(new RdfQueryException("Calling code does not have permission to access the specified remote endpoint, see inner exception for details", secEx), state));
                            }
                            catch (WebException webEx)
                            {
                                if (webEx.Response != null)
                                {
                                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                                }
                                callback(null, handler, new AsyncError(new RdfQueryException("A HTTP error occurred while making an asynchronous query, see inner exception for details", webEx), state));
                            }
                            catch (Exception ex)
                            {
                                callback(null, handler, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
                            }
                        }, null);
                    }
                    catch (WebException webEx)
                    {
                        if (webEx.Response != null)
                        {
                            Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        }
                        callback(null, handler, new AsyncError(new RdfQueryException("A HTTP error occurred while making an asynchronous query, see inner exception for details", webEx), state));
                    }
                    catch (Exception ex)
                    {
                        callback(null, handler, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
                    }
                }, null);
            }
            catch (Exception ex)
            {
                callback(null, handler, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
            }
        }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Makes a SPARQL Query against the underlying Store processing the results with 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 virtual void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
        {
            try
            {
                //Pre-parse the query to determine what the Query Type is
                bool        isAsk = false;
                SparqlQuery q     = null;
                try
                {
                    q     = this._parser.ParseFromString(sparqlQuery);
                    isAsk = q.QueryType == SparqlQueryType.Ask;
                }
                catch
                {
                    //If parsing error fallback to naive detection
                    isAsk = Regex.IsMatch(sparqlQuery, "ASK", RegexOptions.IgnoreCase);
                }

                //Select Accept Header
                String accept;
                if (q != null)
                {
                    accept = (SparqlSpecsHelper.IsSelectQuery(q.QueryType) || q.QueryType == SparqlQueryType.Ask ? MimeTypesHelper.HttpSparqlAcceptHeader : MimeTypesHelper.HttpAcceptHeader);
                }
                else
                {
                    accept = MimeTypesHelper.HttpRdfOrSparqlAcceptHeader;
                }

                HttpWebRequest request;

                //Create the Request
                Dictionary <String, String> queryParams = new Dictionary <string, string>();
                if (sparqlQuery.Length < 2048 && !this._postAllQueries)
                {
                    queryParams.Add("query", EscapeQuery(sparqlQuery));

                    request = this.CreateRequest(this._repositoriesPrefix + this._store + this._queryPath, accept, "GET", queryParams);
                }
                else
                {
                    request = this.CreateRequest(this._repositoriesPrefix + this._store + this._queryPath, 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(Uri.EscapeDataString(EscapeQuery(sparqlQuery)));
                    StreamWriter writer = new StreamWriter(request.GetRequestStream());
                    writer.Write(postData);
                    writer.Close();
                }

#if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugRequest(request);
                }
#endif

                //Get the Response and process based on the Content Type
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    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, isAsk);
                        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);
                        if (q != null && (SparqlSpecsHelper.IsSelectQuery(q.QueryType) || q.QueryType == SparqlQueryType.Ask))
                        {
                            SparqlRdfParser resreader = new SparqlRdfParser(rdfreader);
                            resreader.Load(resultsHandler, data);
                        }
                        else
                        {
                            rdfreader.Load(rdfHandler, data);
                        }
                        response.Close();
                    }
                }
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
#endif
                    if (webEx.Response.ContentLength > 0)
                    {
                        try
                        {
                            String responseText = new StreamReader(webEx.Response.GetResponseStream()).ReadToEnd();
                            throw new RdfQueryException("A HTTP error occured while querying the Store.  Store returned the following error message: " + responseText, webEx);
                        }
                        catch
                        {
                            throw new RdfQueryException("A HTTP error occurred while querying the Store", webEx);
                        }
                    }
                    else
                    {
                        throw new RdfQueryException("A HTTP error occurred while querying the Store", webEx);
                    }
                }
                else
                {
                    throw new RdfQueryException("A HTTP error occurred while querying the Store", webEx);
                }
            }
        }
Ejemplo n.º 7
0
        static void DoQuery(Dictionary <String, String> arguments)
        {
            SparqlRemoteEndpoint endpoint;
            bool verbose = arguments.ContainsKey("verbose") || arguments.ContainsKey("v");

            if (verbose)
            {
                Options.HttpDebugging = true;
            }

            //First get the Server to which we are going to connect
            try
            {
                if (arguments.ContainsKey("server") && !arguments["server"].Equals(String.Empty))
                {
                    endpoint = new SparqlRemoteEndpoint(new Uri(arguments["server"]));
                }
                else if (arguments.ContainsKey("service") && !arguments["service"].Equals(String.Empty))
                {
                    endpoint = new SparqlRemoteEndpoint(new Uri(arguments["service"]));
                }
                else
                {
                    Console.Error.WriteLine("soh: Error: Required --server/--service argument not present");
                    Environment.Exit(-1);
                    return;
                }
            }
            catch (UriFormatException uriEx)
            {
                Console.Error.WriteLine("soh: Error: Malformed SPARQL Endpoint URI");
                Console.Error.WriteLine(uriEx.Message);
                Environment.Exit(-1);
                return;
            }
            if (verbose)
            {
                Console.Error.WriteLine("soh: SPARQL Endpoint for URI " + endpoint.Uri + " created OK");
            }

            //Then decide where to get the query to execute from
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       query;

            try
            {
                if (arguments.ContainsKey("query") && !arguments["query"].Equals(String.Empty))
                {
                    query = parser.ParseFromFile(arguments["query"]);
                }
                else if (arguments.ContainsKey("file") && !arguments["file"].Equals(String.Empty))
                {
                    query = parser.ParseFromFile(arguments["file"]);
                }
                else if (arguments.ContainsKey("$1") && !arguments["$1"].Equals(String.Empty))
                {
                    query = parser.ParseFromString(arguments["$1"]);
                }
                else
                {
                    Console.Error.WriteLine("soh: Error: Required SPARQL Query not found - may be specified as --file/--query FILE or as final argument");
                    Environment.Exit(-1);
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("soh: Error: Error Parsing SPARQL Query");
                Console.Error.WriteLine(ex.Message);
                Environment.Exit(-1);
                return;
            }

            if (verbose)
            {
                Console.Error.WriteLine("soh: Parsed Query OK");
                Console.Error.WriteLine("soh: dotNetRDF's interpretation of the Query:");
                SparqlFormatter formatter = new SparqlFormatter();
                Console.Error.WriteLine(formatter.Format(query));
                Console.Error.WriteLine("soh: Submitting Query");
            }

            try
            {
                using (HttpWebResponse response = endpoint.QueryRaw(query.ToString()))
                {
                    MimeTypeDefinition definition = MimeTypesHelper.GetDefinitions(response.ContentType).FirstOrDefault();
                    Encoding           enc;
                    if (definition != null)
                    {
                        enc = definition.Encoding;
                    }
                    else if (!response.ContentEncoding.Equals(String.Empty))
                    {
                        enc = Encoding.GetEncoding(response.ContentEncoding);
                    }
                    else if (response.ContentType.Contains("charset="))
                    {
                        enc = Encoding.GetEncoding(response.ContentType.Substring(response.ContentType.IndexOf('=') + 1));
                    }
                    else
                    {
                        enc = Console.OutputEncoding;
                    }

                    if (verbose)
                    {
                        Console.Error.WriteLine("soh: Got Response from SPARQL Endpoint OK");
                        Console.Error.WriteLine("soh: Content-Type: " + response.ContentType);
                        Console.Error.WriteLine("soh: Content-Encoding: " + enc.WebName);
                    }

                    String requestedType = arguments.ContainsKey("accept") ? arguments["accept"] : null;

                    if (requestedType == null || response.ContentType.StartsWith(requestedType, StringComparison.OrdinalIgnoreCase))
                    {
                        //If no --accept (OR matches servers content type) then just return whatever the server has given us
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(), enc))
                            {
                                while (!reader.EndOfStream)
                                {
                                    writer.WriteLine(reader.ReadLine());
                                }
                                writer.Close();
                            }
                            reader.Close();
                        }
                    }
                    else
                    {
                        if (verbose)
                        {
                            Console.Error.WriteLine("soh: Warning: Retrieved Content Type '" + response.ContentType + "' does not match your desired Content Type '" + requestedType + "' so dotNetRDF will not attempt to transcode the response into your desired format");
                        }

                        //Requested Type Doesn't match servers returned type so parse then serialize
                        MimeTypeDefinition outputDefinition;
                        try
                        {
                            ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                            SparqlResultSet      results      = new SparqlResultSet();
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                sparqlParser.Load(results, reader);
                                reader.Close();
                            }

                            outputDefinition = MimeTypesHelper.GetDefinitions(requestedType).FirstOrDefault(d => d.CanWriteSparqlResults || d.CanWriteRdf);
                            if (outputDefinition == null)
                            {
                                throw new RdfWriterSelectionException("No MIME Type Definition for the MIME Type '" + requestedType + "' was found that can write SPARQL Results/RDF");
                            }
                            ISparqlResultsWriter writer = outputDefinition.GetSparqlResultsWriter();
                            Console.OutputEncoding = outputDefinition.Encoding;
                            writer.Save(results, new StreamWriter(Console.OpenStandardOutput(), outputDefinition.Encoding));
                        }
                        catch (RdfParserSelectionException)
                        {
                            try
                            {
                                IRdfReader rdfParser = MimeTypesHelper.GetParser(response.ContentType);
                                Graph      g         = new Graph();
                                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                                {
                                    rdfParser.Load(g, reader);
                                    reader.Close();
                                }

                                outputDefinition = MimeTypesHelper.GetDefinitions(requestedType).FirstOrDefault(d => d.CanWriteRdf);
                                if (outputDefinition == null)
                                {
                                    throw new RdfWriterSelectionException("No MIME Type Definition for the MIME Type '" + requestedType + "' was found that can write RDF");
                                }
                                IRdfWriter writer = outputDefinition.GetRdfWriter();
                                Console.OutputEncoding = outputDefinition.Encoding;
                                writer.Save(g, new StreamWriter(Console.OpenStandardOutput(), outputDefinition.Encoding));
                            }
                            catch (Exception ex)
                            {
                                //For any other exception show a warning
                                Console.Error.WriteLine("soh: Warning: You wanted results in the format '" + requestedType + "' but the server returned '" + response.ContentType + "' and dotNetRDF was unable to translate the response into your desired format.");
                                Console.Error.WriteLine(ex.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            //For any other exception show a warning
                            Console.Error.WriteLine("soh: Warning: You wanted results in the format '" + requestedType + "' but the server returned '" + response.ContentType + "' and dotNetRDF was unable to translate the response into your desired format.");
                            Console.Error.WriteLine(ex.Message);
                        }
                    }


                    response.Close();
                }

                if (verbose)
                {
                    Console.Error.WriteLine("soh: Query Completed OK");
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("soh: Error: Error while making the SPARQL Query");
                Console.Error.WriteLine(ex.Message);
                Environment.Exit(-1);
                return;
            }
        }
Ejemplo n.º 8
0
        private void btnOpenQueryResults_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Uri    u        = new Uri(this.txtEndpoint.Text);
                String defGraph = this.txtDefaultGraph.Text;
                SparqlRemoteEndpoint endpoint;
                if (String.IsNullOrEmpty(defGraph))
                {
                    endpoint = new SparqlRemoteEndpoint(u);
                }
                else
                {
                    endpoint = new SparqlRemoteEndpoint(u, defGraph);
                }
                String[] accept = MimeTypesHelper.HttpRdfOrSparqlAcceptHeader.Split(',');
                if (!String.IsNullOrEmpty(this.txtAcceptHeader.Text))
                {
                    accept = this.txtAcceptHeader.Text.Split(',');
                }

                String data;
                using (HttpWebResponse response = endpoint.QueryRaw(this._editor.DocumentManager.ActiveDocument.Text, accept))
                {
                    data = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    try
                    {
                        this._parser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                    }
                    catch (RdfParserSelectionException)
                    {
                        //Ignore here we'll try other means of getting a parser after this
                    }
                    response.Close();
                }

                this._data = data;
                if (this._parser == null)
                {
                    try
                    {
                        this._parser = StringParser.GetResultSetParser(this._data);
                    }
                    catch (RdfParserSelectionException)
                    {
                        this._parser = null;
                    }
                }

                this.DialogResult = true;
                this.Close();
            }
            catch (UriFormatException)
            {
                MessageBox.Show("You have failed to enter a valid Endpoint URI", "Invalid URI");
            }
            catch (WebException webEx)
            {
                MessageBox.Show("A HTTP error occurred making the Query: " + webEx.Message, "Open Query Results Failed");
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while making the Query: " + ex.Message, "Open Query Results Failed");
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Makes a SPARQL Query against the Joseki store processing the results with the 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
                Dictionary <String, String> queryParams = new Dictionary <string, string>();
                if (sparqlQuery.Length < 2048)
                {
                    queryParams.Add("query", sparqlQuery);

                    request = this.CreateRequest(this._queryService, MimeTypesHelper.HttpRdfOrSparqlAcceptHeader, "GET", queryParams);
                }
                else
                {
                    request = this.CreateRequest(this._queryService, MimeTypesHelper.HttpRdfOrSparqlAcceptHeader, "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();
                }

#if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugRequest(request);
                }
#endif

                //Get the Response and process based on the Content Type
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    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();
                    }
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                }
#endif
                throw new RdfQueryException("A HTTP error occurred while querying the Store", webEx);
            }
        }