/// <summary>
        /// Creates a new Parser Context
        /// </summary>
        /// <param name="reader">XML Reader</param>
        /// <param name="handler">Results Handler</param>
        public SparqlXmlParserContext(XmlReader reader, ISparqlResultsHandler handler)
            : base(handler)
        {
            if (reader == null) throw new ArgumentNullException("reader");

            this._reader = reader;
        }
Exemple #2
0
 /// <summary>
 /// Executes a SPARQL Query on the Graph handling the results with the given handlers
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">SPARQL Results Handler</param>
 /// <param name="sparqlQuery">SPARQL Query</param>
 public void ExecuteQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
 {
     if (this._store == null)
     {
         this._store = new TripleStore();
         this._store.Add(this);
     }
     this._store.ExecuteQuery(rdfHandler, resultsHandler, sparqlQuery);
 }
 public void ExecuteSparql(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery, IStore store)
 {
     try
     {
         var query = ParseSparql(sparqlQuery);
         var queryProcessor = new BrightstarQueryProcessor(store, new StoreSparqlDataset(store));
         queryProcessor.ProcessQuery(rdfHandler, resultsHandler, query);
     }
     catch (Exception ex)
     {
         Logging.LogError(BrightstarEventId.SparqlExecutionError,
                          "Error Executing Sparql {0}. Cause: {1}",
                          sparqlQuery, ex);
         throw;
     }
 }
Exemple #4
0
 /// <summary>
 /// Loads a Result Set from a File using a Results Handler
 /// </summary>
 /// <param name="handler">Results Handler to use</param>
 /// <param name="filename">Filename to load from</param>
 public void Load(ISparqlResultsHandler handler, string filename)
 {
     if (filename == null) throw new RdfParseException("Cannot parse SPARQL Results from a null file");
     this.Load(handler, new StreamReader(filename));
 }
 /// <summary>
 /// Executes a SPARQL Query on 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 void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
 {
     this._queryManager.Query(rdfHandler, resultsHandler, sparqlQuery);
 }
 /// <summary>
 /// Processes a SPARQL Query passing the results to the RDF or Results handler as appropriate
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="query">SPARQL Query</param>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
 {
     #if !SILVERLIGHT
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         this._svc.Query(rdfHandler, resultsHandler, query.ToString());
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = (DateTime.Now - start);
     }
     #else
     throw new NotSupportedException("Synchronous remote query is not supported under Silverlight/WP7 - please use one of the alternative overload of this methods which takes a callback");
     #endif
 }
Exemple #7
0
        /// <summary>
        /// Executes a SPARQL Query on the Triple 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="query">SPARQL Query as unparsed String</param>
        public virtual void ExecuteQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String query)
        {
            //Parse the Query
            SparqlQueryParser sparqlparser = new SparqlQueryParser();
            SparqlQuery q = sparqlparser.ParseFromString(query);

            //Invoke other execute method
            this.ExecuteQuery(rdfHandler, resultsHandler, q);
        }
Exemple #8
0
        /// <summary>
        /// Makes a SPARQL Query against the Store processing the results with the appropriate processor from those given
        /// </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)
        {
            if (this._queryParser == null) this._queryParser = new SparqlQueryParser();
            SparqlQuery q = this._queryParser.ParseFromString(sparqlQuery);

            if (this._queryProcessor == null) this._queryProcessor = new LeviathanQueryProcessor(this._dataset);
            this._queryProcessor.ProcessQuery(rdfHandler, resultsHandler, q);
        }
 /// <summary>
 /// Parser method which parses the Stream as Json
 /// </summary>
 /// <param name="input">Input Stream</param>
 /// <param name="handler">Results Handler</param>
 private void Parse(TextReader input, ISparqlResultsHandler handler)
 {
     this.ParseResultSetObject(new SparqlJsonParserContext(new CommentIgnoringJsonTextReader(input), handler));
 }
 /// <summary>
 /// Processes a SPARQL Query passing the results to the RDF or Results handler as appropriate
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="query">SPARQL Query</param>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
 {
     query.QueryTime = -1;
     query.QueryTimeTicks = -1;
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         this._svc.Query(rdfHandler, resultsHandler, query.ToString());
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = (DateTime.Now - start);
         query.QueryTime = elapsed.Milliseconds;
         query.QueryTimeTicks = elapsed.Ticks;
     }
 }
 /// <summary>
 /// Creates a new Results Parser Context
 /// </summary>
 /// <param name="handler">Results Handler</param>
 public BaseResultsParserContext(ISparqlResultsHandler handler)
     : this(handler, false) { }
 /// <summary>
 /// Creates a new Parser Context
 /// </summary>
 /// <param name="handler">Results Handler</param>
 /// <param name="traceParsing">Whether to trace parsing</param>
 public BaseResultsParserContext(ISparqlResultsHandler handler, bool traceParsing)
 {
     if (handler == null) throw new ArgumentNullException("handler");
     this._handler = handler;
     this._traceParsing = traceParsing;
 }
 /// <summary>
 /// Creates a new Tokenising Parser Context with custom settings
 /// </summary>
 /// <param name="handler">Results Handler</param>
 /// <param name="tokeniser">Tokeniser to use</param>
 /// <param name="queueMode">Tokeniser Queue Mode</param>
 /// <param name="traceParsing">Whether to trace parsing</param>
 /// <param name="traceTokeniser">Whether to trace tokenisation</param>
 public TokenisingResultParserContext(ISparqlResultsHandler handler, ITokeniser tokeniser, TokenQueueMode queueMode, bool traceParsing, bool traceTokeniser)
     : base(handler, traceParsing)
 {
     switch (queueMode)
     {
         case TokenQueueMode.AsynchronousBufferDuringParsing:
             this._queue = new AsynchronousBufferedTokenQueue(tokeniser);
             break;
         case TokenQueueMode.SynchronousBufferDuringParsing:
             this._queue = new BufferedTokenQueue(tokeniser);
             break;
         case TokenQueueMode.QueueAllBeforeParsing:
         default:
             this._queue = new TokenQueue(tokeniser);
             break;
     }
     this._traceTokeniser = traceTokeniser;
     this._queue.Tracing = this._traceTokeniser;
 }
 /// <summary>
 /// Creates a new Tokenising Parser Context with custom settings
 /// </summary>
 /// <param name="handler">Results Handler</param>
 /// <param name="tokeniser">Tokeniser to use</param>
 /// <param name="traceParsing">Whether to trace parsing</param>
 /// <param name="traceTokeniser">Whether to trace tokenisation</param>
 public TokenisingResultParserContext(ISparqlResultsHandler handler, ITokeniser tokeniser, bool traceParsing, bool traceTokeniser)
     : this(handler, tokeniser)
 {
     this._traceParsing = traceParsing;
     this._traceTokeniser = traceTokeniser;
     this._queue.Tracing = this._traceTokeniser;
 }
        /// <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 = (HttpWebRequest)WebRequest.Create(this._endpoint.Uri);
                request.Accept      = accept;
                request.Method      = "POST";
                request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded;
                request             = base.ApplyRequestOptions(request);

                Tools.HttpDebugRequest(request);

                request.BeginGetRequestStream(r =>
                {
                    try
                    {
                        Stream stream = request.EndGetRequestStream(r);
                        using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8)))
                        {
                            writer.Write("query=");
                            writer.Write(HttpUtility.UrlEncode(sparqlQuery));
                            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();
                                }
                                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);
            }
        }
Exemple #16
0
 /// <summary>
 /// Processes a SPARQL Query passing the results to the RDF or Results handler as appropriate
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="query">SPARQL Query</param>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
 {
     #if !SILVERLIGHT
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         switch (query.QueryType)
         {
             case SparqlQueryType.Ask:
             case SparqlQueryType.Select:
             case SparqlQueryType.SelectAll:
             case SparqlQueryType.SelectAllDistinct:
             case SparqlQueryType.SelectAllReduced:
             case SparqlQueryType.SelectDistinct:
             case SparqlQueryType.SelectReduced:
                 this._endpoint.QueryWithResultSet(resultsHandler, this._formatter.Format(query));
                 break;
             case SparqlQueryType.Construct:
             case SparqlQueryType.Describe:
             case SparqlQueryType.DescribeAll:
                 this._endpoint.QueryWithResultGraph(rdfHandler, this._formatter.Format(query));
                 break;
             default:
                 throw new RdfQueryException("Unable to execute an unknown query type against a Remote Endpoint");
         }
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = elapsed;
     }
     #else
     throw new NotSupportedException("Synchronous remote query is not supported under Silverlight/WP7 - please use one of the alternative overload of this methods which takes a callback");
     #endif
 }
Exemple #17
0
        /// <summary>
        /// Processes a SPARQL Query against the Knowledge Base passing the results to the RDF or Results handler as appropriate
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="callback">Callback to invoke once handling of results has completed</param>
        /// <param name="state">State to pass to the callback</param>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery, QueryCallback callback, Object state)
        {
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(sparqlQuery);

            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri));
            switch (q.QueryType)
            {
                case SparqlQueryType.Ask:
                case SparqlQueryType.Select:
                case SparqlQueryType.SelectAll:
                case SparqlQueryType.SelectAllDistinct:
                case SparqlQueryType.SelectAllReduced:
                case SparqlQueryType.SelectDistinct:
                case SparqlQueryType.SelectReduced:
                    endpoint.QueryWithResultSet(sparqlQuery, (rs, _) =>
                        {
                            resultsHandler.Apply(rs);
                            callback(rdfHandler, resultsHandler, state);
                        }, state);
                    break;
                case SparqlQueryType.Construct:
                case SparqlQueryType.Describe:
                case SparqlQueryType.DescribeAll:
                    endpoint.QueryWithResultGraph(sparqlQuery, (g, _) =>
                        {
                            rdfHandler.Apply(g);
                            callback(rdfHandler, resultsHandler, state);
                        }, state);
                    break;

                default:
                    throw new RdfQueryException("Cannot execute unknown query types against Pellet Server");
            }
        }
Exemple #18
0
 /// <summary>
 /// Processes a SPARQL Query asynchronously passing the results to the relevant handler and invoking the callback when the query completes
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="query">SPARQL Query</param>
 /// <param name="callback">Callback</param>
 /// <param name="state">State to pass to the callback</param>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query, QueryCallback callback, Object state)
 {
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         switch (query.QueryType)
         {
             case SparqlQueryType.Ask:
             case SparqlQueryType.Select:
             case SparqlQueryType.SelectAll:
             case SparqlQueryType.SelectAllDistinct:
             case SparqlQueryType.SelectAllReduced:
             case SparqlQueryType.SelectDistinct:
             case SparqlQueryType.SelectReduced:
                 this._endpoint.QueryWithResultSet(resultsHandler, this._formatter.Format(query), callback, state);
                 break;
             case SparqlQueryType.Construct:
             case SparqlQueryType.Describe:
             case SparqlQueryType.DescribeAll:
                 this._endpoint.QueryWithResultGraph(rdfHandler, this._formatter.Format(query), callback, state);
                 break;
             default:
                 throw new RdfQueryException("Unable to execute an unknown query type against a Remote Endpoint");
         }
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = elapsed;
     }
 }
 /// <summary>
 /// Loads a Result Set from an Input Stream using a Results Handler
 /// </summary>
 /// <param name="handler">Results Handler to use</param>
 /// <param name="input">Input Stream to read from</param>
 public void Load(ISparqlResultsHandler handler, StreamReader input)
 {
     this.Load(handler, (TextReader)input);
 }
Exemple #20
0
 /// <summary>
 /// Processes a SPARQL Query passing the results to the RDF or Results handler as appropriate
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="query">SPARQL Query</param>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
 {
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         this._store.ExecuteQuery(rdfHandler, resultsHandler, this._formatter.Format(query));
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = elapsed;
     }
 }
        /// <summary>
        /// Loads a Result Set from an Input using a Results Handler
        /// </summary>
        /// <param name="handler">Results Handler to use</param>
        /// <param name="input">Input to read from</param>
        public void Load(ISparqlResultsHandler handler, TextReader input)
        {
            if (handler == null) throw new RdfParseException("Cannot read SPARQL Results using a null Results Handler");
            if (input == null) throw new RdfParseException("Cannot read SPARQL Results from a null Input");

            try
            {
                this.Parse(input, handler);
            }
            catch
            {
                throw;
            }
            finally
            {
                try
                {
                    input.Close();
                }
                catch
                {
                    //No catch actions - just trying to cleanup
                }
            }
        }
Exemple #22
0
 /// <summary>
 /// Processes a SPARQL Query asynchronously passing the results to the relevant handler and invoking the callback when the query completes
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="query">SPARQL Query</param>
 /// <param name="callback">Callback</param>
 /// <param name="state">State to pass to the callback</param>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query, QueryCallback callback, Object state)
 {
     ProcessQueryAsync d = new ProcessQueryAsync(this.ProcessQuery);
     d.BeginInvoke(rdfHandler, resultsHandler, query, r =>
     {
         d.EndInvoke(r);
         callback(rdfHandler, resultsHandler, state);
     }, state);
 }
 /// <summary>
 /// Makes a query against the in-memory copy of the Stores data processing the results with one of the given handlers
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="sparqlQuery">SPARQL Query</param>
 public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
 {
     this._store.ExecuteQuery(rdfHandler, resultsHandler, sparqlQuery);
 }
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
 {
     this._underlyingProcessor.ProcessQuery(rdfHandler, resultsHandler, query);
 }
Exemple #25
0
 /// <summary>
 /// Executes a SPARQL Query on the Triple 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="query">SPARQL Query as unparsed String</param>
 public virtual void ExecuteQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
 {
     query.Evaluate(rdfHandler, resultsHandler, this);
 }
 /// <summary>
 /// Provides the required SPARQL query interface for the <see cref="BrightstarIOManager"/> used for SPARQL update support
 /// </summary>
 /// <param name="rdfHandler"></param>
 /// <param name="resultsHandler"></param>
 /// <param name="sparqlQuery"></param>
 /// <param name="store"></param>
 public void ExecuteSparql(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, string sparqlQuery, IStore store)
 {
     try
     {
         var query = ParseSparql(sparqlQuery);
         var dataset = MakeDataset(store);
         if (_defaultGraphUris != null)
         {
             dataset.SetDefaultGraph(_defaultGraphUris);
         }
         var queryProcessor = new BrightstarQueryProcessor(store, dataset);
         queryProcessor.ProcessQuery(rdfHandler, resultsHandler, query);
     }
     catch (Exception ex)
     {
         Logging.LogError(BrightstarEventId.SparqlExecutionError,
                          "Error Executing Sparql {0}. Cause: {1}",
                          sparqlQuery, ex);
         throw;
     }
 }
Exemple #27
0
 /// <summary>
 /// Processes a SPARQL Query asynchronously passing the results to the relevant handler and invoking the callback when the query completes
 /// </summary>
 /// <param name="rdfHandler">RDF Handler</param>
 /// <param name="resultsHandler">Results Handler</param>
 /// <param name="query">SPARQL Query</param>
 /// <param name="callback">Callback</param>
 /// <param name="state">State to pass to the callback</param>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query, QueryCallback callback, Object state)
 {
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         this._svc.Query(rdfHandler, resultsHandler, query.ToString(), callback, state);
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = (DateTime.Now - start);
     }
 }
        /// <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);
                }
            }
        }
Exemple #29
0
        /// <summary>
        /// Loads a Result Set from an Input Stream using a Results Handler
        /// </summary>
        /// <param name="handler">Results Handler to use</param>
        /// <param name="input">Input Stream to read from</param>
        public void Load(ISparqlResultsHandler handler, StreamReader input)
        {
            if (input == null) throw new RdfParseException("Cannot parser SPARQL Results from a null input stream");

            //Check Encoding
            if (input.CurrentEncoding != Encoding.UTF8)
            {
            #if !SILVERLIGHT
                this.RaiseWarning("Expected Input Stream to be encoded as UTF-8 but got a Stream encoded as " + input.CurrentEncoding.EncodingName + " - Please be aware that parsing errors may occur as a result");
            #else
                this.RaiseWarning("Expected Input Stream to be encoded as UTF-8 but got a Stream encoded as " + input.CurrentEncoding.GetType().Name + " - Please be aware that parsing errors may occur as a result");
            #endif
            }

            this.Load(handler, (TextReader)input);
        }
Exemple #30
0
        /// <summary>
        /// Processes a SPARQL Query against the Knowledge Base passing the results to the RDF or Results handler as appropriate
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        /// <param name="sparqlQuery">SPARQL Query</param>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
        {
            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri));

            using (HttpWebResponse response = endpoint.QueryRaw(sparqlQuery))
            {
                try
                {
                    ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                    sparqlParser.Load(resultsHandler, new StreamReader(response.GetResponseStream()));
                }
                catch (RdfParserSelectionException)
                {
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(rdfHandler, new StreamReader(response.GetResponseStream()));
                }
                response.Close();
            }
        }
Exemple #31
0
        /// <summary>
        /// Loads a Result Set from an Input using a Results Handler
        /// </summary>
        /// <param name="handler">Results Handler to use</param>
        /// <param name="input">Input to read from</param>
        public void Load(ISparqlResultsHandler handler, TextReader input)
        {
            if (handler == null) throw new RdfParseException("Cannot parse SPARQL Results into a null Result Handler");
            if (input == null) throw new RdfParseException("Cannot parse SPARQL Results from a null input stream");

            try
            {
                TokenisingResultParserContext context = new TokenisingResultParserContext(handler, new CsvTokeniser(BlockingTextReader.Create(input)));
                this.TryParseResults(context);
                input.Close();
            }
            catch
            {
                try
                {
                    input.Close();
                }
                catch
                {
                    //No catch actions just trying to clean up
                }
                throw;
            }
        }
        /// <summary>
        /// Processes a SPARQL Query sending the results to a RDF/SPARQL Results handler as appropriate.
        /// </summary>
        /// <param name="rdfHandler">RDF Handler.</param>
        /// <param name="resultsHandler">Results Handler.</param>
        /// <param name="query">SPARQL Query.</param>
        public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
        {
            // Do Handler null checks before evaluating the query
            if (query == null)
            {
                throw new ArgumentNullException("query", "Cannot evaluate a null query");
            }
            if (rdfHandler == null && (query.QueryType == SparqlQueryType.Construct || query.QueryType == SparqlQueryType.Describe || query.QueryType == SparqlQueryType.DescribeAll))
            {
                throw new ArgumentNullException("rdfHandler", "Cannot use a null RDF Handler when the Query is a CONSTRUCT/DESCRIBE");
            }
            if (resultsHandler == null && (query.QueryType == SparqlQueryType.Ask || SparqlSpecsHelper.IsSelectQuery(query.QueryType)))
            {
                throw new ArgumentNullException("resultsHandler", "Cannot use a null resultsHandler when the Query is an ASK/SELECT");
            }

            // Handle the Thread Safety of the Query Evaluation
            ReaderWriterLockSlim currLock = (_dataset is IThreadSafeDataset) ? ((IThreadSafeDataset)_dataset).Lock : _lock;

            try
            {
                currLock.EnterReadLock();
                // Reset Query Timers
                query.QueryExecutionTime = null;

                bool datasetOk = false, defGraphOk = false;

                try
                {
                    // Set up the Default and Active Graphs
                    if (query.DefaultGraphs.Any())
                    {
                        // Call HasGraph() on each Default Graph but ignore the results, we just do this
                        // in case a dataset has any kind of load on demand behaviour
                        foreach (Uri defGraphUri in query.DefaultGraphs)
                        {
                            _dataset.HasGraph(defGraphUri);
                        }
                        _dataset.SetDefaultGraph(query.DefaultGraphs);
                        defGraphOk = true;
                    }
                    else if (query.NamedGraphs.Any())
                    {
                        // No FROM Clauses but one/more FROM NAMED means the Default Graph is the empty graph
                        _dataset.SetDefaultGraph(Enumerable.Empty <Uri>());
                    }
                    _dataset.SetActiveGraph(_dataset.DefaultGraphUris);
                    datasetOk = true;

                    // Convert to Algebra and execute the Query
                    SparqlEvaluationContext context = GetContext(query);
                    BaseMultiset            result;
                    try
                    {
                        context.StartExecution();
                        ISparqlAlgebra algebra = query.ToAlgebra();
                        result = context.Evaluate(algebra);

                        context.EndExecution();
                        query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks);
                    }
                    catch (RdfQueryException)
                    {
                        context.EndExecution();
                        query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks);
                        throw;
                    }
                    catch
                    {
                        context.EndExecution();
                        query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks);
                        throw;
                    }

                    // Return the Results
                    switch (query.QueryType)
                    {
                    case SparqlQueryType.Ask:
                    case SparqlQueryType.Select:
                    case SparqlQueryType.SelectAll:
                    case SparqlQueryType.SelectAllDistinct:
                    case SparqlQueryType.SelectAllReduced:
                    case SparqlQueryType.SelectDistinct:
                    case SparqlQueryType.SelectReduced:
                        // For SELECT and ASK can populate a Result Set directly from the Evaluation Context
                        // return new SparqlResultSet(context);
                        resultsHandler.Apply(context);
                        break;

                    case SparqlQueryType.Construct:
                        // Create a new Empty Graph for the Results
                        try
                        {
                            rdfHandler.StartRdf();

                            foreach (String prefix in query.NamespaceMap.Prefixes)
                            {
                                if (!rdfHandler.HandleNamespace(prefix, query.NamespaceMap.GetNamespaceUri(prefix)))
                                {
                                    ParserHelper.Stop();
                                }
                            }

                            // Construct the Triples for each Solution
                            if (context.OutputMultiset is IdentityMultiset)
                            {
                                context.OutputMultiset = new SingletonMultiset();
                            }
                            foreach (ISet s in context.OutputMultiset.Sets)
                            {
                                // List<Triple> constructedTriples = new List<Triple>();
                                try
                                {
                                    ConstructContext constructContext = new ConstructContext(rdfHandler, s, false);
                                    foreach (IConstructTriplePattern p in query.ConstructTemplate.TriplePatterns.OfType <IConstructTriplePattern>())
                                    {
                                        try

                                        {
                                            if (!rdfHandler.HandleTriple(p.Construct(constructContext)))
                                            {
                                                ParserHelper.Stop();
                                            }
                                            // constructedTriples.Add(((IConstructTriplePattern)p).Construct(constructContext));
                                        }
                                        catch (RdfQueryException)
                                        {
                                            // If we get an error here then we could not construct a specific triple
                                            // so we continue anyway
                                        }
                                    }
                                }
                                catch (RdfQueryException)
                                {
                                    // If we get an error here this means we couldn't construct for this solution so the
                                    // entire solution is discarded
                                    continue;
                                }
                                // h.Assert(constructedTriples);
                            }
                            rdfHandler.EndRdf(true);
                        }
                        catch (RdfParsingTerminatedException)
                        {
                            rdfHandler.EndRdf(true);
                        }
                        catch
                        {
                            rdfHandler.EndRdf(false);
                            throw;
                        }
                        break;

                    case SparqlQueryType.Describe:
                    case SparqlQueryType.DescribeAll:
                        // For DESCRIBE we retrieve the Describe algorithm and apply it
                        ISparqlDescribe describer = query.Describer;
                        describer.Describe(rdfHandler, context);
                        break;

                    default:
                        throw new RdfQueryException("Unknown query types cannot be processed by Leviathan");
                    }
                }
                finally
                {
                    if (defGraphOk)
                    {
                        _dataset.ResetDefaultGraph();
                    }
                    if (datasetOk)
                    {
                        _dataset.ResetActiveGraph();
                    }
                }
            }
            finally
            {
                currLock.ExitReadLock();
            }
        }