/// <summary>
 /// Executes a SPARQL Query on the Graph.
 /// </summary>
 /// <param name="query">SPARQL Query.</param>
 /// <returns></returns>
 public Object ExecuteQuery(SparqlQuery query)
 {
     if (_processor == null)
     {
         InMemoryDataset ds = new InMemoryDataset(this);
         _processor = new LeviathanQueryProcessor(ds);
     }
     return(_processor.ProcessQuery(query));
 }
        private void TestResultCountHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            SparqlResultSet expected = processor.ProcessQuery(q) as SparqlResultSet;

            Assert.NotNull(expected);

            ResultCountHandler handler = new ResultCountHandler();

            processor.ProcessQuery(null, handler, q);

            Assert.Equal(expected.Count, handler.Count);
        }
        private void TestCountHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            Graph expected = processor.ProcessQuery(q) as Graph;

            Assert.NotNull(expected);

            CountHandler handler = new CountHandler();

            processor.ProcessQuery(handler, null, q);

            Assert.Equal(expected.Triples.Count, handler.Count);
        }
        private void TestGraphHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            Graph expected = processor.ProcessQuery(q) as Graph;

            Assert.NotNull(expected);

            Graph        actual  = new Graph();
            GraphHandler handler = new GraphHandler(actual);

            processor.ProcessQuery(handler, null, q);

            Assert.Equal(expected, actual);
        }
Пример #5
0
        public object ExecuteQuery(string query)
        {
            SparqlQueryParser sparqlparser = new SparqlQueryParser();
            var q = sparqlparser.ParseFromString(query.ToString());

            return(_queryProcessor.ProcessQuery(q));
        }
Пример #6
0
        public IEnumerable <Dictionary <string, string> > Process(string query)
        {
            var parsedQuery = _sparqlQueryParser.ParseFromString(query);
            var resObj      = _queryProc.ProcessQuery(parsedQuery);

            if (resObj is SparqlResultSet results)
            {
                foreach (var result in results)
                {
                    var resDic = new Dictionary <string, string>();
                    foreach (var item in result)
                    {
                        string value;
                        if (item.Value is LiteralNode node)
                        {
                            value = node.Value;
                        }
                        else
                        {
                            value = item.Value.ToString();
                        }
                        resDic[item.Key] = value;
                    }
                    yield return(resDic);
                }
            }
            else
            {
                throw new ExtensionException(Name, "Wrong query type");
            }
        }
        public Stream ExecuteQuery(string queryExpression, IList <string> datasetGraphUris)
        {
            var parser        = new SparqlQueryParser();
            var query         = parser.ParseFromString(queryExpression);
            var sparqlResults = _queryProcessor.ProcessQuery(query);
            var memoryStream  = new MemoryStream();

            using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8))
            {
                if (sparqlResults is SparqlResultSet)
                {
                    var resultSet = sparqlResults as SparqlResultSet;
                    var writer    = new SparqlXmlWriter();
                    writer.Save(resultSet, streamWriter);
                }
                else if (sparqlResults is IGraph)
                {
                    var g      = sparqlResults as IGraph;
                    var writer = new RdfXmlWriter();
                    writer.Save(g, streamWriter);
                }
            }
            return(new MemoryStream(memoryStream.ToArray()));
            //return new MemoryStream(Encoding.UTF8.GetBytes(buff.ToString()), false);
        }
        public SparqlResult ExecuteQuery(SparqlQueryContext queryContext, IList <string> datasetGraphUris)
        {
            var parser        = new SparqlQueryParser();
            var query         = parser.ParseFromString(queryContext.SparqlQuery);
            var sparqlResults = _queryProcessor.ProcessQuery(query);

            return(new SparqlResult(sparqlResults, queryContext));
        }
        private void TestCountHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            Graph expected = processor.ProcessQuery(q) as Graph;

            if (expected == null)
            {
                Assert.Fail("Query failed to return a Graph as expected");
            }

            CountHandler handler = new CountHandler();

            processor.ProcessQuery(handler, null, q);

            Assert.AreEqual(expected.Triples.Count, handler.Count, "Counts should have been equal");
        }
        private void TestResultCountHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            SparqlResultSet expected = processor.ProcessQuery(q) as SparqlResultSet;

            if (expected == null)
            {
                Assert.Fail("Query failed to return a Result Set as expected");
            }

            ResultCountHandler handler = new ResultCountHandler();

            processor.ProcessQuery(null, handler, q);

            Assert.AreEqual(expected.Count, handler.Count, "Counts should have been equal");
        }
        private void TestResultSetHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            SparqlResultSet expected = processor.ProcessQuery(q) as SparqlResultSet;

            if (expected == null)
            {
                Assert.Fail("Query failed to return a Result Set as expected");
            }

            SparqlResultSet  actual  = new SparqlResultSet();
            ResultSetHandler handler = new ResultSetHandler(actual);

            processor.ProcessQuery(null, handler, q);

            Assert.AreEqual(expected, actual, "Result Sets should be equal");
        }
        private void TestGraphHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            Graph expected = processor.ProcessQuery(q) as Graph;

            if (expected == null)
            {
                Assert.Fail("Query failed to return a Grah as expected");
            }

            Graph        actual  = new Graph();
            GraphHandler handler = new GraphHandler(actual);

            processor.ProcessQuery(handler, null, q);

            Assert.AreEqual(expected, actual, "Graphs should be equal");
        }
Пример #13
0
        /// <summary>
        /// This method queries the dotNetRdf store directly.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public object ExecuteQuery(string query)
        {
            Log?.Invoke(query);

            SparqlQueryParser parser = new SparqlQueryParser();

            var q = parser.ParseFromString(query);

            return(_queryProcessor.ProcessQuery(q));
        }
        /// <summary>
        /// Executes this command as a query
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        public void ExecuteQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler)
        {
            if (_queryProcessor == null)
            {
                throw new RdfQueryException("Cannot call ExecuteQuery() when the QueryProcessor property has not been set");
            }

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(ToString());

            _queryProcessor.ProcessQuery(rdfHandler, resultsHandler, q);
        }
        private void TestWriteThroughHandler(ISparqlQueryProcessor processor, String query)
        {
            NTriplesFormatter formatter = new NTriplesFormatter();
            StringWriter      data      = new StringWriter();

            SparqlQuery q        = this._parser.ParseFromString(query);
            Graph       expected = processor.ProcessQuery(q) as Graph;

            Assert.NotNull(expected);

            WriteThroughHandler handler = new WriteThroughHandler(formatter, data, false);

            processor.ProcessQuery(handler, null, q);
            Console.WriteLine(data.ToString());

            Graph actual = new Graph();

            StringParser.Parse(actual, data.ToString(), new NTriplesParser());

            Assert.Equal(expected, actual);
        }
        private SparqlResultSet QueryWithResults(SparqlQuery q, ISparqlQueryProcessor processor)
        {
            var results = processor.ProcessQuery(q);

            if (results is SparqlResultSet)
            {
                return((SparqlResultSet)results);
            }
            else
            {
                Assert.True(false, "Query did not produce a Result Set as expected");
            }
            return(null);
        }
        private IGraph QueryWithGraph(SparqlQuery q, ISparqlQueryProcessor processor)
        {
            var results = processor.ProcessQuery(q);

            if (results is IGraph)
            {
                return((IGraph)results);
            }
            else
            {
                Assert.True(false, "Query did not produce a Graph as expected");
            }
            return(null);
        }
        private void TestWriteThroughHandler(ISparqlQueryProcessor processor, String query)
        {
            NTriplesFormatter formatter = new NTriplesFormatter();
            StringWriter      data      = new StringWriter();

            SparqlQuery q        = this._parser.ParseFromString(query);
            Graph       expected = processor.ProcessQuery(q) as Graph;

            if (expected == null)
            {
                Assert.Fail("Query did not produce a Graph as expected");
            }

            WriteThroughHandler handler = new WriteThroughHandler(formatter, data, false);

            processor.ProcessQuery(handler, null, q);
            Console.WriteLine(data.ToString());

            Graph actual = new Graph();

            StringParser.Parse(actual, data.ToString(), new NTriplesParser());

            Assert.AreEqual(expected, actual, "Graphs should be equal");
        }
        public SparqlResultSet ExecuteQuery(string query)
        {
            var queryString = new SparqlParameterizedString(query);

            foreach (var prefix in namespaceMapper.Prefixes)
            {
                if (!queryString.Namespaces.HasNamespace(prefix))
                {
                    queryString.Namespaces.AddNamespace(prefix, namespaceMapper.GetNamespaceUri(prefix));
                }
            }
            var parsed = sparqlQueryParser.ParseFromString(queryString);

            return((SparqlResultSet)sparqlProcessor.ProcessQuery(parsed));
        }
Пример #20
0
        public AndConstraint <StoreAssertions> MatchAsk(
            Action <ITriplePatternBuilder> getPtterns,
            Func <INonAggregateExpressionBuilder, BooleanExpression> getFilters = null)
        {
            var queryBuilder = QueryBuilder.Ask().Where(getPtterns);

            if (getFilters != null)
            {
                queryBuilder.Filter(getFilters);
            }

            var query     = queryBuilder.BuildQuery();
            var askResult = (SparqlResultSet)queryProcessor.ProcessQuery(queryBuilder.BuildQuery());

            askResult.Result.Should().BeTrue("Dataset contents should match query:{0}{1}", Environment.NewLine, query);

            return(new AndConstraint <StoreAssertions>(this));
        }
Пример #21
0
        private AndConstraint <StoreAssertions> VerifyAskQuery(
            Action <ITriplePatternBuilder> buildPatterns,
            bool expectedResult,
            Func <ExpressionBuilder, BooleanExpression> filter = null)
        {
            var ask = QueryBuilder.Ask().Where(buildPatterns);

            if (filter != null)
            {
                ask.Filter(filter);
            }

            var sparqlQuery = ask.BuildQuery();
            var result      = (SparqlResultSet)_queryProcessor.ProcessQuery(sparqlQuery);

            result.Result.Should().Be(expectedResult, "RDF data should match query '{0}'", sparqlQuery);

            return(new AndConstraint <StoreAssertions>(this));
        }
Пример #22
0
        /// <summary>
        /// Processes a SPARQL Query using given SPARQL procesor returning either an IGraph instance or SparqlResultSet, or AsyncError if the processing failed
        /// </summary>
        /// <returns>IGraph or SparqlResultSet or AsyncError or null</returns>
        public static Task <object> ProcessQuery(SparqlQuery query, ISparqlQueryProcessor processor)
        {
            TaskCompletionSource <object> taskComplSource = new TaskCompletionSource <object>();

            if (query == null || processor == null)
            {
                var asyncError = new AsyncError(new BrowserException("An internal error occured while processing the query."), null);
                taskComplSource.SetResult(asyncError);
            }
            else
            {
                //state will contain AsyncError
                //catches all exceptions inside, putting them into AsyncError
                processor.ProcessQuery(
                    query,
                    (IGraph g, object state) => { taskComplSource.SetResult(g ?? state); },
                    (SparqlResultSet results, object state) => { taskComplSource.SetResult(results ?? state); },
                    null
                    );
            }
            return(taskComplSource.Task);
        }
Пример #23
0
    public SparqlResultSet Execute(string queryExpr, IDictionary <string, INode> paramValues = null)
    {
        var queryString = new SparqlParameterizedString(queryExpr);

        // Import namespace presets.
        foreach (var prefix in namespaceMapper.Prefixes)
        {
            if (!queryString.Namespaces.HasNamespace(prefix))
            {
                queryString.Namespaces.AddNamespace(prefix, namespaceMapper.GetNamespaceUri(prefix));
            }
        }
        // Apply parameters.
        if (paramValues != null)
        {
            foreach (var(name, value) in paramValues)
            {
                queryString.SetParameter(name, value);
            }
        }
        // Parse the query.
        var query = GuardedParseQueryString(queryString);

        foreach (var prefix in namespaceMapper.Prefixes)
        {
            if (!query.NamespaceMap.HasNamespace(prefix))
            {
                query.NamespaceMap.AddNamespace(prefix, namespaceMapper.GetNamespaceUri(prefix));
            }
        }
        var result = queryProcessor.ProcessQuery(query);

        if (!(result is SparqlResultSet resultSet))
        {
            throw new NotSupportedException("Persisting AOT query results other than SparqlResultSet is not supported.");
        }
        return(resultSet);
    }
Пример #24
0
        private IGraph QueryForCurrentState()
        {
            // throw new NotImplementedException();
            var ps = new SparqlParameterizedString();

            ps.CommandText = @"
                PREFIX mig: <http://industrialinference.com/migrations/0.1#>
                CONSTRUCT {
		            [] a mig:Migration ;
			            mig:ordinal ?ordinal ;
			            mig:dtApplied ?dtApplied ;
                        mig:appliedBy ?appliedBy ;
                        mig:migrationHash ?migrationHash;
                        mig:migratorVersion ?migratorVersion;
                        mig:originalPath ?originalPath .
                }
                WHERE {
	                GRAPH mig:migrations {
		                _:mig a mig:Migration ;
			                mig:ordinal ?ordinal ;
			                mig:dtApplied ?dtApplied ;
                            mig:appliedBy ?appliedBy ;
                            mig:migrationHash ?migrationHash;
                            mig:migratorVersion ?migratorVersion;
                            mig:originalPath ?originalPath .
                        }
                    }";

            var parser = new SparqlQueryParser();
            var query  = parser.ParseFromString(ps);
            var result = _queryProcessor.ProcessQuery(query) as IGraph;

            result?.NamespaceMap.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
            result?.NamespaceMap.AddNamespace("mig", new Uri("http://industrialinference.com/migrations/0.1#"));
            return(result);
        }
Пример #25
0
        private static Collection<BaprLocation> ExecuteQuery(ISparqlQueryProcessor processor, SparqlQuery query)
        {
            try
            {
                object queryResult = processor.ProcessQuery(query);
                if (queryResult is SparqlResultSet)
                {
                    SparqlResultSet entities = (SparqlResultSet)queryResult;
                    return BaprAPI.Utils.Utils.ConvertFromSparqlSetToBaprLocations(entities);
                }
            }
            catch (VDS.RDF.Query.RdfQueryException ex)
            {

            }
            return new Collection<BaprLocation>();
        }
Пример #26
0
        /// <summary>
        /// Does the SPARQL query then returns the result set
        /// </summary>
        public static SparqlResultSet DoQuery(string str)
        {
            SparqlQuery query = sparqlparser.ParseFromString(str);

            return((SparqlResultSet)processor.ProcessQuery(query));
        }
Пример #27
0
 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;
 }
Пример #28
0
 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;
 }
Пример #29
0
 /// <summary>
 /// Processes the Query using the given Query Processor
 /// </summary>
 /// <param name="processor">SPARQL Query Processor</param>
 /// <returns></returns>
 public Object Process(ISparqlQueryProcessor processor)
 {
     return(processor.ProcessQuery(this));
 }
Пример #30
0
 /// <summary>
 /// Processes the Query using the given Query Processor
 /// </summary>
 /// <param name="processor">SPARQL Query Processor</param>
 /// <returns></returns>
 public Object Process(ISparqlQueryProcessor processor)
 {
     return processor.ProcessQuery(this);
 }
        /// <summary>
        /// Processes a PUT operation
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public override void ProcessPut(IHttpContext context)
        {
            // Get the payload assuming there is one
            IGraph g = ParsePayload(context);

            // Get the Graph URI of the Graph to be added
            Uri graphUri = ResolveGraphUri(context, g);

            // Determine whether the Graph already exists or not, if it doesn't then we have to send a 201 Response
            bool created = false;

            try
            {
                SparqlQueryParser         parser           = new SparqlQueryParser();
                SparqlParameterizedString graphExistsQuery = new SparqlParameterizedString();
                graphExistsQuery.CommandText = "ASK WHERE { GRAPH @graph { } }";
                graphExistsQuery.SetUri("graph", graphUri);

                Object temp = _queryProcessor.ProcessQuery(parser.ParseFromString(graphExistsQuery));
                if (temp is SparqlResultSet)
                {
                    created = !((SparqlResultSet)temp).Result;
                }
            }
            catch
            {
                // If any error occurs assume the Graph doesn't exist and so we'll return a 201 created
                created = true;
            }

            // Generate a set of commands based upon this
            StringBuilder cmdSequence = new StringBuilder();

            if (graphUri != null)
            {
                cmdSequence.AppendLine("DROP SILENT GRAPH @graph ;");
                cmdSequence.Append("CREATE SILENT GRAPH @graph");
            }
            else
            {
                cmdSequence.Append("DROP SILENT DEFAULT");
            }
            if (g != null)
            {
                cmdSequence.AppendLine(" ;");
                if (graphUri != null)
                {
                    cmdSequence.AppendLine("INSERT DATA { GRAPH @graph {");
                }
                else
                {
                    cmdSequence.AppendLine("INSERT DATA { ");
                }

                TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap);
                foreach (Triple t in g.Triples)
                {
                    cmdSequence.AppendLine(t.ToString(formatter));
                }

                if (graphUri != null)
                {
                    cmdSequence.AppendLine("} }");
                }
                else
                {
                    cmdSequence.AppendLine("}");
                }
            }

            SparqlParameterizedString put = new SparqlParameterizedString(cmdSequence.ToString());

            put.Namespaces = g.NamespaceMap;
            if (graphUri != null)
            {
                put.SetUri("graph", graphUri);
            }
            SparqlUpdateCommandSet putCmds = _parser.ParseFromString(put);

            _updateProcessor.ProcessCommandSet(putCmds);
            _updateProcessor.Flush();

            // Return a 201 if required, otherwise the default behaviour of returning a 200 will occur automatically
            if (created)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Created;
            }
        }
        public SparqlResultSet QueryFromFile(string filePath)
        {
            SparqlQuery query = _sqlQueryParser.ParseFromFile(filePath);

            return((SparqlResultSet)_processor.ProcessQuery(query));
        }