示例#1
0
        public fclsInspect(SparqlQuery query, long parseTime, String origQuery)
        {
            InitializeComponent();

            this.lblParseTime.Text = "Took " + parseTime + "ms to parse";
            this.txtQuery.Text = this._formatter.Format(query);
            this.txtAlgebra.Text = query.ToAlgebra().ToString();

            //Compute the actual syntax compatability
            SparqlQueryParser parser = new SparqlQueryParser();
            parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_0;
            try
            {
                SparqlQuery q = parser.ParseFromString(origQuery);
                this.lblSyntaxCompatability.Text += " SPARQL 1.0 (Standard)";
            }
            catch
            {
                try
                {
                    parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_1;
                    SparqlQuery q = parser.ParseFromString(origQuery);
                    this.lblSyntaxCompatability.Text += " SPARQL 1.1 (Current Working Draft Standard)";
                }
                catch
                {
                    parser.SyntaxMode = SparqlQuerySyntax.Extended;
                    SparqlQuery q = parser.ParseFromString(origQuery);
                    this.lblSyntaxCompatability.Text += " SPARQL 1.1 (Implementation specific extensions)";
                }
            }
        }
 /// <summary>
 /// Executes a SPARQL Query on the Graph
 /// </summary>
 /// <param name="query">SPARQL Query</param>
 /// <returns></returns>
 public Object ExecuteQuery(SparqlQuery query)
 {
     if (this._store == null)
     {
         this._store = new TripleStore();
         this._store.Add(this);
     }
     return this._store.ExecuteQuery(query);
 }
        /// <summary>
        /// Creates a new Evaluation Context for the given Query over the given Dataset
        /// </summary>
        /// <param name="q">Query</param>
        /// <param name="data">Dataset</param>
        public SparqlEvaluationContext(SparqlQuery q, ISparqlDataset data)
        {
            this._query = q;
            this._data = data;
            this._inputSet = new IdentityMultiset();
            this._binder = new LeviathanResultBinder(this);

            this.CalculateTimeout();
        }
示例#4
0
        /// <summary>
        /// Creates a new SPARQL View
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="store">Triple Store to query</param>
        public BaseSparqlView(String sparqlQuery, ITripleStore store)
        {
            SparqlQueryParser parser = new SparqlQueryParser();
            this._q = parser.ParseFromString(sparqlQuery);
            this._store = store;

            this._async = new UpdateViewDelegate(this.UpdateViewInternal);
            this.Initialise();
        }
示例#5
0
 /// <summary>
 /// Processes the SPARQL Query using the underlying processor and then
 /// </summary>
 /// <param name="query"></param>
 /// <param name="sink"></param>
 public void Run(SparqlQuery query, ILinqResultsSink sink)
 {
     Object results = this.ProcessQuery(query);
     if (results is SparqlResultSet)
     {
         sink.Fill((SparqlResultSet)results);
     }
     else if (results is BaseMultiset)
     {
         sink.Fill((BaseMultiset)results);
     }
     else
     {
         throw new LinqToRdfException("Underlying Query Processor returned unexpected results of type " + results.GetType().ToString());
     }
 }
示例#6
0
 /// <summary>
 /// Processes a SPARQL Query
 /// </summary>
 /// <param name="query">SPARQL Query</param>
 /// <returns></returns>
 public object ProcessQuery(SparqlQuery query)
 {
     query.QueryExecutionTime = null;
     query.QueryTime = -1;
     query.QueryTimeTicks = -1;
     DateTime start = DateTime.Now;
     try
     {
         Object temp = this._store.ExecuteQuery(this._formatter.Format(query));
         return temp;
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = elapsed;
         query.QueryTime = elapsed.Milliseconds;
         query.QueryTimeTicks = elapsed.Ticks;
     }
 }
        public fclsExplanation(SparqlQuery query, long parseTime)
        {
            InitializeComponent();

            this.lblParseTime.Text = "Took " + parseTime + "ms to parse";
            this.txtQuery.Text = this._formatter.Format(query);

            //First need to create the Explanation
            using (StreamWriter writer = new StreamWriter("explain.temp", false, Encoding.UTF8))
            {
                ExplainQueryProcessor processor = new ExplainQueryProcessor(new TripleStore());
                processor.ExplanationLevel = (ExplanationLevel.OutputToTrace | ExplanationLevel.ShowAll | ExplanationLevel.AnalyseAll | ExplanationLevel.Simulate) ^ ExplanationLevel.ShowThreadID ^ ExplanationLevel.ShowTimings ^ ExplanationLevel.ShowIntermediateResultCount;

                TextWriterTraceListener listener = new TextWriterTraceListener(writer, "SparqlGUI");
                Trace.Listeners.Add(listener);
                try
                {
                    Object results = processor.ProcessQuery(query);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    Trace.Listeners.Remove(listener);
                }

                writer.Close();
            }

            //Then need to display it
            using (StreamReader reader = new StreamReader("explain.temp"))
            {
                this.txtExplanation.Text = reader.ReadToEnd();
                reader.Close();
            }
        }
示例#8
0
        private void TestProductTimeout(IGraph data, String query, bool useGlobal, int expectedResults)
        {
            Console.WriteLine("Maximum Expected Results: " + expectedResults);
            Console.WriteLine("Initial Global Timeout: " + Options.QueryExecutionTimeout);
            Console.WriteLine();

            long globalOrig = Options.QueryExecutionTimeout;

            try
            {
                if (useGlobal)
                {
                    Console.WriteLine("Global Timeout setting in use");
                }
                else
                {
                    Console.WriteLine("Per Query Timeout setting in use");
                }
                Console.WriteLine();

                TripleStore store = new TripleStore();
                store.Add(data);

                SparqlQuery             q         = this._parser.ParseFromString(query);
                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));

                SparqlFormatter formatter = new SparqlFormatter();
                Console.WriteLine("Query:");
                Console.WriteLine(formatter.Format(q));

                //Evaluate for each Timeout
                foreach (long t in this._timeouts)
                {
                    //Set the Timeout and ask for Partial Results
                    if (useGlobal)
                    {
                        Options.QueryExecutionTimeout = t;
                    }
                    else
                    {
                        q.Timeout = t;
                    }
                    q.PartialResultsOnTimeout = true;

                    //Check that the reported Timeout matches the expected
                    SparqlEvaluationContext context = new SparqlEvaluationContext(q, null);
                    long expected;
                    if (useGlobal)
                    {
                        expected = t;
                    }
                    else
                    {
                        if (Options.QueryExecutionTimeout > 0 && t <= Options.QueryExecutionTimeout)
                        {
                            expected = t;
                        }
                        else if (Options.QueryExecutionTimeout == 0)
                        {
                            expected = t;
                        }
                        else
                        {
                            expected = Options.QueryExecutionTimeout;
                        }
                    }
                    Assert.AreEqual(expected, context.QueryTimeout, "Reported Timeout not as expected");

                    //Run the Query
                    Object results = processor.ProcessQuery(q);
                    if (results is SparqlResultSet)
                    {
                        SparqlResultSet rset = (SparqlResultSet)results;

                        Console.WriteLine("Requested Timeout: " + t + " - Actual Timeout: " + expected + "ms - Results: " + rset.Count + " - Query Time: " + q.QueryExecutionTime);
                        Assert.IsTrue(rset.Count <= expectedResults, "Results should be <= expected");
                    }
                    else
                    {
                        Assert.Fail("Did not get a Result Set as expected");
                    }
                }
            }
            finally
            {
                Options.QueryExecutionTimeout = globalOrig;
            }
        }
 private IGraph QueryWithGraph(SparqlQuery q, ISparqlQueryProcessor processor)
 {
     Object results = processor.ProcessQuery(q);
     if (results is IGraph)
     {
         return (IGraph)results;
     }
     else
     {
         Assert.Fail("Query did not produce a Graph as expected");
     }
     return null;
 }
示例#10
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
            {
                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
        }
示例#11
0
        /// <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
#if !NO_RWLOCK
            ReaderWriterLockSlim currLock = (this._dataset is IThreadSafeDataset) ? ((IThreadSafeDataset)this._dataset).Lock : this._lock;
            try
            {
                currLock.EnterReadLock();
#endif
            //Reset Query Timers
            query.QueryExecutionTime = null;
            query.QueryTime          = -1;
            query.QueryTimeTicks     = -1;

            bool datasetOk = false, defGraphOk = false;

            try
            {
                //Set up the Default and Active Graphs
                IGraph defGraph;
                if (query.DefaultGraphs.Any())
                {
                    //Default Graph is the Merge of all the Graphs specified by FROM clauses
                    Graph g = new Graph();
                    foreach (Uri u in query.DefaultGraphs)
                    {
                        if (this._dataset.HasGraph(u))
                        {
                            g.Merge(this._dataset[u], true);
                        }
                        else
                        {
                            throw new RdfQueryException("A Graph with URI '" + u.ToString() + "' does not exist in this Triple Store, this URI cannot be used in a FROM clause in SPARQL queries to this Triple Store");
                        }
                    }
                    defGraph = g;
                    this._dataset.SetDefaultGraph(defGraph);
                }
                else if (query.NamedGraphs.Any())
                {
                    //No FROM Clauses but one/more FROM NAMED means the Default Graph is the empty graph
                    defGraph = new Graph();
                    this._dataset.SetDefaultGraph(defGraph);
                }
                else
                {
                    defGraph = this._dataset.DefaultGraph;
                    this._dataset.SetDefaultGraph(defGraph);
                }
                defGraphOk = true;
                this._dataset.SetActiveGraph(defGraph);
                datasetOk = true;

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

                    context.EndExecution();
                    query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks);
                    query.QueryTime          = context.QueryTime;
                    query.QueryTimeTicks     = context.QueryTimeTicks;
                }
                catch (RdfQueryException)
                {
                    context.EndExecution();
                    query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks);
                    query.QueryTime          = context.QueryTime;
                    query.QueryTimeTicks     = context.QueryTimeTicks;
                    throw;
                }
                catch
                {
                    context.EndExecution();
                    query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks);
                    query.QueryTime          = context.QueryTime;
                    query.QueryTimeTicks     = 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
                        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)
                {
                    this._dataset.ResetDefaultGraph();
                }
                if (datasetOk)
                {
                    this._dataset.ResetActiveGraph();
                }
            }
#if !NO_RWLOCK
        }

        finally
        {
            currLock.ExitReadLock();
        }
#endif
        }
示例#12
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
            {
                _svc.Query(rdfHandler, resultsHandler, query.ToString());
            }
            finally
            {
                TimeSpan elapsed = (DateTime.Now - start);
                query.QueryExecutionTime = (DateTime.Now - start);
            }
        }
示例#13
0
 public BrightstarSparqlResultsType ExecuteSparqlQuery(SparqlQuery query, ISerializationFormat targetFormat, Stream resultsStream,
     IEnumerable<string> defaultGraphUris )
 {
     var queryHandler = new SparqlQueryHandler(targetFormat, defaultGraphUris);
     // NOTE: streamWriter is not wrapped in a using because we don't want to close resultStream at this point
     
     var streamWriter = new StreamWriter(resultsStream, targetFormat.Encoding);
     var resultsType = queryHandler.ExecuteSparql(query, this, streamWriter);
     return resultsType;
 }
示例#14
0
        public void SparqlBgpEvaluation()
        {
            //Prepare the Store
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "Turtle.ttl");
            store.Add(g);

            SparqlQueryParser parser     = new SparqlQueryParser();
            SparqlQuery       q          = parser.ParseFromString(@"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT * WHERE {?s ?p ?o . ?s rdfs:label ?label}");
            Object            testResult = store.ExecuteQuery(q);

            ISparqlAlgebra testAlgebra = q.ToAlgebra();

            if (testResult is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)testResult;
                Console.WriteLine(rset.Count + " Results");
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Console.WriteLine();
            }

            //Create some Triple Patterns
            TriplePattern t1 = new TriplePattern(new VariablePattern("?s"), new VariablePattern("?p"), new VariablePattern("?o"));
            TriplePattern t2 = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(g.CreateUriNode("rdfs:label")), new VariablePattern("?label"));
            TriplePattern t3 = new TriplePattern(new VariablePattern("?x"), new VariablePattern("?y"), new VariablePattern("?z"));
            TriplePattern t4 = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(g.CreateUriNode(":name")), new VariablePattern("?name"));

            //Build some BGPs
            Bgp selectNothing  = new Bgp();
            Bgp selectAll      = new Bgp(t1);
            Bgp selectLabelled = new Bgp(new List <ITriplePattern>()
            {
                t1, t2
            });
            Bgp selectAllDisjoint = new Bgp(new List <ITriplePattern>()
            {
                t1, t3
            });
            Bgp selectLabels = new Bgp(t2);
            Bgp selectNames  = new Bgp(t4);
            //LeftJoin selectOptionalNamed = new LeftJoin(selectAll, new Optional(selectNames));
            LeftJoin selectOptionalNamed = new LeftJoin(selectAll, selectNames);
            Union    selectAllUnion      = new Union(selectAll, selectAll);
            Union    selectAllUnion2     = new Union(selectAllUnion, selectAll);
            Filter   selectAllUriObjects = new Filter(selectAll, new UnaryExpressionFilter(new IsUriFunction(new VariableTerm("o"))));

            //Test out the BGPs
            //Console.WriteLine("{}");
            //this.ShowMultiset(selectNothing.Evaluate(new SparqlEvaluationContext(null, store)));

            //Console.WriteLine("{?s ?p ?o}");
            //this.ShowMultiset(selectAll.Evaluate(new SparqlEvaluationContext(null, store)));

            //Console.WriteLine("{?s ?p ?o . ?s rdfs:label ?label}");
            //SparqlEvaluationContext context = new SparqlEvaluationContext(null, store);
            //this.ShowMultiset(selectLabelled.Evaluate(context));
            //SparqlResultSet lvnResult = new SparqlResultSet(context);

            //Console.WriteLine("{?s ?p ?o . ?x ?y ?z}");
            //this.ShowMultiset(selectAllDisjoint.Evaluate(new SparqlEvaluationContext(null, store)));

            //Console.WriteLine("{?s ?p ?o . OPTIONAL {?s :name ?name}}");
            //this.ShowMultiset(selectOptionalNamed.Evaluate(new SparqlEvaluationContext(null, store)));

            Console.WriteLine("{{?s ?p ?o} UNION {?s ?p ?o}}");
            this.ShowMultiset(selectAllUnion.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store))));

            Console.WriteLine("{{?s ?p ?o} UNION {?s ?p ?o} UNION {?s ?p ?o}}");
            this.ShowMultiset(selectAllUnion2.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store))));

            Console.WriteLine("{?s ?p ?o FILTER (ISURI(?o))}");
            this.ShowMultiset(selectAllUriObjects.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store))));
        }
        private void CheckQueryParsesInExtended(String query)
        {
            SparqlQuery q = this._parserExt.ParseFromString(query);

            Console.WriteLine("Query Parses under SPARQL 1.1 with Extensions as expected");
        }
        /// <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 override void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query)
        {
            query.QueryExecutionTime = null;
            var start = DateTime.Now;

            try
            {
                _store.ExecuteQuery(rdfHandler, resultsHandler, _formatter.Format(query));
            }
            finally
            {
                var elapsed = (DateTime.Now - start);
                query.QueryExecutionTime = elapsed;
            }
        }
示例#17
0
        public void SparqlPropertyPathParser()
        {
            //Load our test data
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            List <String> testQueries = new List <string>();
            String        rdfsPrefix  = "PREFIX rdfs: <" + NamespaceMapper.RDFS + ">\n";

            //Cardinality Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf* <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf+ <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf? <http://example.org/vehicles/Vehicle>}");
            //testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2,4} <http://example.org/vehicles/Vehicle>}");
            //testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2,} <http://example.org/vehicles/Vehicle>}");
            //testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{,4} <http://example.org/vehicles/Vehicle>}");
            //testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2} <http://example.org/vehicles/Vehicle>}");

            //Simple Inverse Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?type ^a ?entity}");

            //Sequence Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf / rdfs:subClassOf <http://example.org/vehicles/Vehicle>}");
            //testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf{2} / rdfs:subClassOf <http://example.org/vehicles/Vehicle>}");
            //testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf / rdfs:subClassOf{2} <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass a / rdfs:subClassOf <http://example.org/vehicles/Plane>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?vehicle a ^ rdfs:subClassOf <http://example.org/vehicles/Plane>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass a / ^ rdfs:subClassOf <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?entity a ^ a ?type}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?entity a ^ a / rdfs:subClassOf <http://example.org/vehicles/GroundVehicle>}");


            //Alternative Paths
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf | a <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass (rdfs:subClassOf | a) | rdfs:someProperty <http://example.org/vehicles/Vehicle>}");
            testQueries.Add(rdfsPrefix + "SELECT * WHERE {?subclass rdfs:subClassOf | a | rdfs:someProperty <http://example.org/vehicles/Vehicle>}");

            SparqlQueryParser parser = new SparqlQueryParser();

            foreach (String query in testQueries)
            {
                //Parse the Query and output to console
                SparqlQuery q = parser.ParseFromString(query);
                Console.WriteLine(q.ToString());

                //Now we'll try and evaluate it (if this is possible)
                try
                {
                    Object results = store.ExecuteQuery(q);

                    Console.WriteLine("Evaluated OK");
                    TestTools.ShowResults(results);
                    Console.WriteLine();
                }
                catch (RdfQueryException queryEx)
                {
                    Console.WriteLine("Unable to evaluate:");
                    Console.WriteLine(queryEx.Message);
                    Console.WriteLine(queryEx.StackTrace);
                }
            }
        }
        internal static void Apply(this ISparqlResultsHandler handler, SparqlEvaluationContext context)
        {
            try
            {
                handler.StartResults();

                SparqlQuery     q = context.Query;
                SparqlQueryType type;
                if (q == null)
                {
                    type = (context.OutputMultiset.Variables.Any() || context.OutputMultiset.Sets.Any() ? SparqlQueryType.Select : SparqlQueryType.Ask);
                }
                else
                {
                    type = q.QueryType;
                }

                if (type == SparqlQueryType.Ask)
                {
                    // ASK Query so get the handler to handle an appropriate boolean result
                    if (context.OutputMultiset is IdentityMultiset)
                    {
                        handler.HandleBooleanResult(true);
                    }
                    else if (context.OutputMultiset is NullMultiset)
                    {
                        handler.HandleBooleanResult(false);
                    }
                    else
                    {
                        handler.HandleBooleanResult(!context.OutputMultiset.IsEmpty);
                    }
                }
                else
                {
                    // SELECT Query so get the handler to handle variables and then handle results
                    foreach (String var in context.OutputMultiset.Variables)
                    {
                        if (!handler.HandleVariable(var))
                        {
                            ParserHelper.Stop();
                        }
                    }
                    foreach (ISet s in context.OutputMultiset.Sets)
                    {
                        if (!handler.HandleResult(new SparqlResult(s)))
                        {
                            ParserHelper.Stop();
                        }
                    }
                    q.VirtualCount = context.OutputMultiset.VirtualCount;
                }

                handler.EndResults(true);
            }
            catch (RdfParsingTerminatedException)
            {
                handler.EndResults(true);
            }
            catch
            {
                handler.EndResults(false);
                throw;
            }
        }
 /// <summary>
 /// Creates a new Evaluation Context for the given Query over the given Dataset using a specific processor
 /// </summary>
 /// <param name="q">Query</param>
 /// <param name="data">Dataset</param>
 /// <param name="processor">Query Processor</param>
 public SparqlEvaluationContext(SparqlQuery q, ISparqlDataset data, ISparqlQueryAlgebraProcessor <BaseMultiset, SparqlEvaluationContext> processor)
     : this(q, data)
 {
     this._processor = processor;
 }
示例#20
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);
            }
        }
示例#21
0
 /// <summary>
 /// Processes a SPARQL Query
 /// </summary>
 /// <param name="query">SPARQL Query</param>
 /// <returns></returns>
 public object ProcessQuery(SparqlQuery query)
 {
     query.QueryTime = -1;
     query.QueryTimeTicks = -1;
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         Object temp = this._svc.Query(query.ToString());
         return temp;
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = (DateTime.Now - start);
         query.QueryTime = elapsed.Milliseconds;
         query.QueryTimeTicks = elapsed.Ticks;
     }
 }
        private void CheckQueryParsesIn11(String query)
        {
            SparqlQuery q = this._parser11.ParseFromString(query);

            Console.WriteLine("Query Parses under SPARQL 1.1 as expected");
        }
 /// <summary>
 /// Determines the Permission Action for a SPARQL Query
 /// </summary>
 /// <param name="query">Query</param>
 /// <returns></returns>
 private String GetPermissionAction(SparqlQuery query)
 {
     switch (query.QueryType)
     {
         case SparqlQueryType.Ask:
             return "ASK";
         case SparqlQueryType.Construct:
             return "CONSTRUCT";
         case SparqlQueryType.Describe:
         case SparqlQueryType.DescribeAll:
             return "DESCRIBE";
         case SparqlQueryType.Select:
         case SparqlQueryType.SelectAll:
         case SparqlQueryType.SelectAllDistinct:
         case SparqlQueryType.SelectAllReduced:
         case SparqlQueryType.SelectDistinct:
         case SparqlQueryType.SelectReduced:
             return "SELECT";
         default:
             return String.Empty;
     }
 }
示例#24
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>
        /// <remarks>
        /// In the event of a success the callback will be invoked, if there is an error the callback will be invoked and passed an instance of <see cref="AsyncError"/> which contains details of the error and the original state information passed in.
        /// </remarks>
        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;
            }
        }
示例#25
0
 /// <summary>
 /// Executes a SPARQL Query on the Triple Store
 /// </summary>
 /// <param name="query">SPARQL Query as a <see cref="SparqlQuery">SparqlQuery</see> instance</param>
 /// <returns></returns>
 public virtual Object ExecuteQuery(SparqlQuery query)
 {
     //Invoke Query's Evaluate method
     return query.Evaluate(this);
 }
示例#26
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;
            }
        }
示例#27
0
 /// <summary>
 /// Creates a new SPARQL View
 /// </summary>
 /// <param name="sparqlQuery">SPARQL Query</param>
 /// <param name="store">Triple Store to query</param>
 public NativeSparqlView(SparqlQuery sparqlQuery, INativelyQueryableStore store)
     : base(sparqlQuery, store) { }
 /// <summary>
 /// Creates a new SPARQL View.
 /// </summary>
 /// <param name="sparqlQuery">SPARQL Query.</param>
 /// <param name="store">Triple Store to query.</param>
 protected BaseSparqlView(SparqlQuery sparqlQuery, ITripleStore store)
 {
     _q     = sparqlQuery;
     _store = store;
     Initialise();
 }
示例#29
0
 /// <summary>
 /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
 /// </summary>
 /// <param name="query">SPARQL QUery</param>
 /// <param name="rdfCallback">Callback for queries that return a Graph</param>
 /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
 /// <param name="state">State to pass to the callback</param>
 public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
 {
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         this._svc.Query(query.ToString(), rdfCallback, resultsCallback, state);
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = (DateTime.Now - start);
     }
 }
        private void SparqlQueryAndUpdateThreadSafeEvaluationActual()
        {
            String query1  = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/1> { ?s ?p ?o } }";
            String query2  = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/2> { ?s ?p ?o } }";
            String query3  = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/3> { ?s ?p ?o } }";
            String update1 = "INSERT DATA { GRAPH <http://example.org/3> { <ex:subj> <ex:pred> <ex:obj> } }";

            SparqlQuery q1 = this._parser.ParseFromString(query1);
            SparqlQuery q2 = this._parser.ParseFromString(query2);
            SparqlQuery q3 = this._parser.ParseFromString(query3);

            Assert.IsFalse(q1.UsesDefaultDataset, "Query 1 should not be thread safe");
            Assert.IsFalse(q2.UsesDefaultDataset, "Query 2 should not be thread safe");
            Assert.IsFalse(q3.UsesDefaultDataset, "Query 3 should not be thread safe");

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(update1);

            InMemoryDataset dataset = new InMemoryDataset();
            Graph           g       = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            g.BaseUri = new Uri("http://example.org/1");
            Graph h = new Graph();

            h.LoadFromEmbeddedResource("VDS.RDF.Query.Expressions.LeviathanFunctionLibrary.ttl");
            h.BaseUri = new Uri("http://example.org/2");
            Graph i = new Graph();

            i.BaseUri = new Uri("http://example.org/3");

            dataset.AddGraph(g);
            dataset.AddGraph(h);
            dataset.AddGraph(i);
            LeviathanQueryProcessor  processor   = new LeviathanQueryProcessor(dataset);
            LeviathanUpdateProcessor upProcessor = new LeviathanUpdateProcessor(dataset);

            QueryWithGraphDelegate d  = new QueryWithGraphDelegate(this.QueryWithGraph);
            RunUpdateDelegate      d2 = new RunUpdateDelegate(this.RunUpdate);
            IAsyncResult           r1 = d.BeginInvoke(q1, processor, null, null);
            IAsyncResult           r2 = d.BeginInvoke(q2, processor, null, null);
            IAsyncResult           r3 = d.BeginInvoke(q3, processor, null, null);
            IAsyncResult           r4 = d2.BeginInvoke(cmds, upProcessor, null, null);

            WaitHandle.WaitAll(new WaitHandle[] { r1.AsyncWaitHandle, r2.AsyncWaitHandle, r3.AsyncWaitHandle, r4.AsyncWaitHandle });

            IGraph gQuery = d.EndInvoke(r1);

            Assert.AreEqual(g, gQuery, "Query 1 Result not as expected");

            IGraph hQuery = d.EndInvoke(r2);

            Assert.AreEqual(h, hQuery, "Query 2 Result not as expected");

            IGraph iQuery = d.EndInvoke(r3);

            if (iQuery.IsEmpty)
            {
                Console.WriteLine("Query 3 executed before the INSERT DATA command - running again to get the resulting graph");
                iQuery = this.QueryWithGraph(q3, processor);
            }
            else
            {
                Console.WriteLine("Query 3 executed after the INSERT DATA command");
            }
            //Test iQuery against an empty Graph
            Assert.IsFalse(iQuery.IsEmpty, "Graph should not be empty as INSERT DATA should have inserted a Triple");
            Assert.AreNotEqual(new Graph(), iQuery, "Graphs should not be equal");

            Assert.AreNotEqual(g, h, "Graphs should not be different");
        }
 /// <summary>
 /// Appends the given query as a sub-query to the existing command text, any prefixes in the sub-query are moved to the parent query.
 /// </summary>
 /// <param name="query">Query.</param>
 public void AppendSubQuery(SparqlQuery query)
 {
     PreprocessText(TrimPreamble(_emptyFormatter.Format(new SubQueryPattern(query))));
     // NOTE: the namespaces are already updated through during the TrimPreambule call
 }
示例#32
0
 /// <summary>
 /// When overridden in a derived class, 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 abstract void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler,
                                   SparqlQuery query);
示例#33
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
        }
示例#34
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>
 /// <remarks>
 /// In the event of a success the callback will be invoked, if there is an error the callback will be invoked and passed an instance of <see cref="AsyncError"/> which contains details of the error and the original state information passed in.
 /// </remarks>
 public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query, QueryCallback callback, object state)
 {
     Task.Factory.StartNew(() => ProcessQuery(rdfHandler, resultsHandler, query))
     .ContinueWith(antecedent =>
     {
         if (antecedent.Exception != null)
         {
             var innerException = antecedent.Exception.InnerExceptions[0];
             var queryException = innerException as RdfQueryException ??
                                  new RdfQueryException(
                 "Unexpected error while making an asynchronous query, see inner exception for details",
                 innerException);
             callback?.Invoke(rdfHandler, resultsHandler, new AsyncError(queryException, state));
         }
         else
         {
             callback?.Invoke(rdfHandler, resultsHandler, state);
         }
     });
 }
 private SparqlResultSet QueryWithResults(SparqlQuery q, ISparqlQueryProcessor processor)
 {
     Object results = processor.ProcessQuery(q);
     if (results is SparqlResultSet)
     {
         return (SparqlResultSet)results;
     }
     else
     {
         Assert.Fail("Query did not produce a Result Set as expected");
     }
     return null;
 }
示例#36
0
 public void SparqlGroupBySample()
 {
     String            query  = "SELECT ?s (SAMPLE(?o) AS ?object) WHERE {?s ?p ?o} GROUP BY ?s";
     SparqlQueryParser parser = new SparqlQueryParser();
     SparqlQuery       q      = parser.ParseFromString(query);
 }
示例#37
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.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;
     }
 }
示例#38
0
 public void SparqlGroupByInSubQuery()
 {
     String            query  = "SELECT ?s WHERE {{SELECT ?s WHERE {?s ?p ?o} GROUP BY ?s}} GROUP BY ?s";
     SparqlQueryParser parser = new SparqlQueryParser();
     SparqlQuery       q      = parser.ParseFromString(query);
 }
 /// <summary>
 /// Processes a Query
 /// </summary>
 /// <param name="query">Query</param>
 /// <returns></returns>
 /// <remarks>
 /// <para>
 /// Implementations should override this method if their behaviour requires more than just invoking the configured Query processor
 /// </para>
 /// </remarks>
 protected virtual Object ProcessQuery(SparqlQuery query)
 {
     return this._config.Processor.ProcessQuery(query);
 }
示例#40
0
 /// <summary>
 /// Creates a new SPARQL View
 /// </summary>
 /// <param name="sparqlQuery">SPARQL Query</param>
 /// <param name="store">Triple Store to query</param>
 public SparqlView(SparqlQuery sparqlQuery, IInMemoryQueryableStore store)
     : base(sparqlQuery, store)
 {
 }
示例#41
0
 public bool IsApplicable(SparqlQuery q)
 {
     return true;
 }
示例#42
0
        /// <summary>
        /// Creates a new SPARQL View
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="store">Triple Store to query</param>
        public BaseSparqlView(SparqlQuery sparqlQuery, ITripleStore store)
        {
            this._q = sparqlQuery;
            this._store = store;

            this._async = new UpdateViewDelegate(this.UpdateViewInternal);
            this.Initialise();
        }
 /// <summary>
 /// Creates a new Evaluation Context for the given Query over the given Dataset using a specific processor
 /// </summary>
 /// <param name="q">Query</param>
 /// <param name="data">Dataset</param>
 /// <param name="processor">Query Processor</param>
 public SparqlEvaluationContext(SparqlQuery q, ISparqlDataset data, ISparqlQueryAlgebraProcessor<BaseMultiset, SparqlEvaluationContext> processor)
     : this(q, data)
 {
     this._processor = processor;
 }
示例#44
0
 private string MakeQueryCacheKey(string storeName, long commitTime, SparqlQuery query, string[] defaultGraphUris, ISerializationFormat targetFormat)
 {
     var graphHashCode = defaultGraphUris == null ? 0 : String.Join(",", defaultGraphUris.OrderBy(s=>s)).GetHashCode();
     return storeName + "_" + commitTime + "_" + query.GetHashCode() + "_" + graphHashCode + "_" + targetFormat;
 }
示例#45
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);
 }
 public BrightstarSparqlResultSet ExecuteSparql(SparqlQuery query, IStore store)
 {
     try
     {
         var dataset = new StoreSparqlDataset(store);
         if (_defaultGraphUris != null)
         {
             dataset.SetDefaultGraph(_defaultGraphUris);
         }
         var queryProcessor = new BrightstarQueryProcessor(store, dataset);
         return new BrightstarSparqlResultSet(queryProcessor.ProcessQuery(query));
     }
     catch (Exception ex)
     {
         Logging.LogError(BrightstarEventId.SparqlExecutionError,
             "Error Executing Sparql {0}. Cause: {1}", 
             query, ex);
         throw;
     }
 }
示例#47
0
 /// <summary>
 /// Creates a new SPARQL View
 /// </summary>
 /// <param name="sparqlQuery">SPARQL Query</param>
 /// <param name="store">Triple Store to query</param>
 public SparqlView(SparqlQuery sparqlQuery, IInMemoryQueryableStore store)
     : base(sparqlQuery, store) { }
示例#48
0
 /// <summary>
 /// Processes a SPARQL Query
 /// </summary>
 /// <param name="query">SPARQL Query</param>
 /// <returns></returns>
 public object ProcessQuery(SparqlQuery query)
 {
     #if !SILVERLIGHT
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         Object temp = this._svc.Query(query.ToString());
         return temp;
     }
     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
 }
示例#49
0
 /// <summary>
 /// Creates a new SPARQL View
 /// </summary>
 /// <param name="sparqlQuery">SPARQL Query</param>
 /// <param name="store">Triple Store to query</param>
 public NativeSparqlView(SparqlQuery sparqlQuery, INativelyQueryableStore store)
     : base(sparqlQuery, store)
 {
 }
示例#50
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);
        }
示例#51
0
 private static bool QueryReturnsGraph(SparqlQuery query)
 {
     return (query.QueryType == SparqlQueryType.Construct ||
             query.QueryType == SparqlQueryType.Describe ||
             query.QueryType == SparqlQueryType.DescribeAll);
 }
示例#52
0
 /// <summary>
 /// Creates a new Results Binder
 /// </summary>
 /// <param name="query">Query this provides Result Binding to</param>
 public SparqlResultBinder(SparqlQuery query)
 {
     this._query = query;
 }
 private void EnsureValidResultFormat(SparqlQuery query)
 {
     if (query.QueryType == SparqlQueryType.Construct ||
         query.QueryType == SparqlQueryType.Describe ||
         query.QueryType == SparqlQueryType.DescribeAll)
     {
         if (_rdfFormat == null) throw new NoAcceptableFormatException(typeof (RdfFormat),
             "CONSTRUCT and DESCRIBE queries require an RdfFormat specifier for the RDF graph serialization.");
     }
     else if (_sparqlResultsFormat == null)
     {
         throw new NoAcceptableFormatException(typeof (SparqlResultsFormat),
             "Query requires a SparqlResultsFormat specifier for the results serialization.");
     }
 }
示例#54
0
        /// <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();
            }
        }
        public BrightstarSparqlResultsType ExecuteSparql(SparqlQuery query, IStore store, TextWriter resultsWriter)
        {
            try
            {
                EnsureValidResultFormat(query);

                var dataset = new StoreSparqlDataset(store);
                if (_defaultGraphUris != null)
                {
                    dataset.SetDefaultGraph(_defaultGraphUris);
                }

                var queryProcessor = new BrightstarQueryProcessor(store, dataset);
                var queryResult = queryProcessor.ProcessQuery(query);
                if (queryResult is SparqlResultSet)
                {
                    var sparqlResultSet = (SparqlResultSet) queryResult;
                    ISparqlResultsWriter sparqlResultsWriter = null;
                    if (_sparqlResultsFormat != null)
                    {
                        sparqlResultsWriter =
                            MimeTypesHelper.GetSparqlWriter(new string[] {_sparqlResultsFormat.ToString()});
                    }
                    if (sparqlResultsWriter == null)
                    {
                        throw new NoAcceptableFormatException(typeof (SparqlResultsFormat),
                                                              "No acceptable format provided for writing a SPARQL result set.");
                    }
                    sparqlResultsWriter.Save(sparqlResultSet, resultsWriter);
                    switch (sparqlResultSet.ResultsType)
                    {
                        case SparqlResultsType.Boolean:
                            return BrightstarSparqlResultsType.Boolean;
                        case SparqlResultsType.VariableBindings:
                            return BrightstarSparqlResultsType.VariableBindings;
                        default:
                            throw new BrightstarInternalException("Unrecognized SPARQL result type");
                    }
                }
                if (queryResult is IGraph)
                {
                    var g = (IGraph) queryResult;
                    var rdfWriter = _rdfFormat == null
                                        ? null
                                        : MimeTypesHelper.GetWriter(new string[] {_rdfFormat.ToString()});
                    if (rdfWriter == null)
                    {
                        throw new NoAcceptableFormatException(typeof (RdfFormat),
                                                              "No acceptable format provided for writing an RDF graph result.");
                    }
                    rdfWriter.Save(g, resultsWriter);
                    return BrightstarSparqlResultsType.Graph;
                }
                throw new BrightstarInternalException(
                    String.Format("Unexpected return type from QueryProcessor.ProcessQuery: {0}",
                                  queryResult.GetType()));
            }
            catch (Exception ex)
            {
                Logging.LogError(BrightstarEventId.SparqlExecutionError,
                                 "Error Executing query {0}. Cause: {1}",
                                 query.ToString(), ex);
                throw;
            }
        }
示例#56
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>
        /// <remarks>
        /// In the event of a success the callback will be invoked, if there is an error the callback will be invoked and passed an instance of <see cref="AsyncError"/> which contains details of the error and the original state information passed in.
        /// </remarks>
        public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query, QueryCallback callback, Object state)
        {
            ProcessQueryAsync d = new ProcessQueryAsync(ProcessQuery);

            d.BeginInvoke(rdfHandler, resultsHandler, query, r =>
            {
                try
                {
                    d.EndInvoke(r);
                    callback(rdfHandler, resultsHandler, state);
                }
                catch (RdfQueryException queryEx)
                {
                    callback(rdfHandler, resultsHandler, new AsyncError(queryEx, state));
                }
                catch (Exception ex)
                {
                    callback(rdfHandler, resultsHandler, new AsyncError(new RdfQueryException("Unexpected error making an asynchronous query", ex), state));
                }
            }, state);
        }
示例#57
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
     {
         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
 }
示例#58
0
 /// <summary>
 /// Creates a new Evaluation Context for the given Query
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 private SparqlEvaluationContext GetContext(SparqlQuery q)
 {
     return(new SparqlEvaluationContext(q, _dataset, GetProcessorForContext()));
 }
示例#59
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);
     }
 }
示例#60
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;
            query.QueryTime          = -1;
            query.QueryTimeTicks     = -1;
            DateTime start = DateTime.Now;

            try
            {
                this._manager.Query(rdfHandler, resultsHandler, this._formatter.Format(query));
            }
            finally
            {
                TimeSpan elapsed = (DateTime.Now - start);
                query.QueryExecutionTime = elapsed;
                query.QueryTime          = elapsed.Milliseconds;
                query.QueryTimeTicks     = elapsed.Ticks;
            }
        }