/// <summary>
 /// Gets the value of the function in the given Evaluation Context for the given Binding ID
 /// </summary>
 /// <param name="context">Evaluation Context</param>
 /// <param name="bindingID">Binding ID</param>
 /// <returns>
 /// Returns a constant Literal Node which is a Date Time typed Literal
 /// </returns>
 public override INode Value(SparqlEvaluationContext context, int bindingID)
 {
     if (this._currQuery == null)
     {
         this._currQuery = context.Query;
     }
     if (this._node == null || !ReferenceEquals(this._currQuery, context.Query))
     {
         this._node = new LiteralNode(null, DateTime.Now.ToString(XmlSpecsHelper.XmlSchemaDateTimeFormat), new Uri(XmlSpecsHelper.XmlSchemaDataTypeDateTime));
         this._ebv = false;
     }
     return this._node;
 }
예제 #2
0
 /// <summary>
 /// Creates a new Sub-query pattern which represents the given sub-query
 /// </summary>
 /// <param name="subquery">Sub-query</param>
 public SubQueryPattern(SparqlQuery subquery)
 {
     this._subquery = subquery;
     this._indexType = TripleIndexType.SpecialSubQuery;
     
     //Get the Variables this query projects out
     foreach (SparqlVariable var in this._subquery.Variables)
     {
         if (var.IsResultVariable)
         {
             this._vars.Add(var.Name);
         }
     }
     this._vars.Sort();
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Result"] == null)
                Response.Redirect("Default.aspx");

            //Get the results
            QueryResult queryResult = (QueryResult)Session["Result"];
            string query = (string)Session["Query"];
            SparqlQuery sparql = new SparqlQuery(query);

            if (queryResult.Status == QueryResultStatus.Ok)
            {
                GridView1.DataSource = queryResult.DataTable;
                GridView1.DataBind();
            }
            else
            {
                ErrorLiteral.Text = queryResult.Message;
            }
        }
예제 #4
0
 /// <summary>
 /// Returns false because this optimiser is never globally applicable.
 /// </summary>
 /// <param name="q">Query.</param>
 /// <returns></returns>
 public bool IsApplicable(SparqlQuery q)
 {
     return(false);
 }
예제 #5
0
 /// <summary>
 /// Creates a new Query Parser Context from the given Token Queue
 /// </summary>
 /// <param name="tokens">Token Queue</param>
 protected internal SparqlQueryParserContext(ITokenQueue tokens)
     : base(new NullHandler(), null)
 {
     this._queue = tokens;
     this._query = new SparqlQuery(true);
 }
예제 #6
0
        internal static INode ToSpinRdf(this SparqlQuery query, IGraph g)
        {
            INode             root     = g.CreateBlankNode();
            SpinVariableTable varTable = new SpinVariableTable(g);

            //Ensure the Query is optimised so that all the elements are placed in Graph Patterns
            //so we can serialized them OK
            query.Optimise();

            switch (query.QueryType)
            {
            case SparqlQueryType.Ask:
                g.Assert(root, RDF.PropertyType, SP.ClassAsk);
                break;

            case SparqlQueryType.Construct:
                g.Assert(root, RDF.PropertyType, SP.ClassConstruct);
                break;

            case SparqlQueryType.Describe:
            case SparqlQueryType.DescribeAll:
                throw new SpinException("DESCRIBE queries cannot be represented in SPIN RDF Syntax");

            case SparqlQueryType.Select:
            case SparqlQueryType.SelectAll:
            case SparqlQueryType.SelectAllDistinct:
            case SparqlQueryType.SelectAllReduced:
            case SparqlQueryType.SelectDistinct:
            case SparqlQueryType.SelectReduced:
                g.Assert(root, RDF.PropertyType, SP.ClassSelect);
                break;

            case SparqlQueryType.Unknown:
                throw new SpinException("Unknown query types cannot be represented in SPIN RDF Syntax");
            }

            //Process the WHERE clause
            g.Assert(root, SP.PropertyWhere, query.RootGraphPattern.ToSpinRdf(g, varTable));

            //Add Variables for a SELECT query
            if (SparqlSpecsHelper.IsSelectQuery(query.QueryType))
            {
                switch (query.QueryType)
                {
                case SparqlQueryType.Select:
                case SparqlQueryType.SelectDistinct:
                case SparqlQueryType.SelectReduced:
                    //Only Add Variables for SELECTs with explicit variable lists
                    INode vars = g.CreateBlankNode();
                    g.Assert(root, SP.PropertyResultVariables, vars);

                    //Get the Variables and generate the Nodes we'll use to help represent them
                    List <SparqlVariable> vs = query.Variables.Where(v => v.IsResultVariable).ToList();

                    for (int i = 0; i < vs.Count; i++)
                    {
                        SparqlVariable v   = vs[i];
                        INode          var = varTable[v.Name];
                        g.Assert(vars, RDF.PropertyFirst, var);
                        if (i < vs.Count - 1)
                        {
                            INode temp = g.CreateBlankNode();
                            g.Assert(vars, RDF.PropertyRest, temp);
                            vars = temp;
                        }
                        // TODO check that was commented before modifications
                        //g.Assert(var, RDF.type, SP.Variable);

                        if (v.IsAggregate)
                        {
                            g.Assert(var, SP.PropertyAs, g.CreateLiteralNode(v.Name, XSD.string_.Uri));
                            g.Assert(var, SP.PropertyExpression, v.Aggregate.ToSpinRdf(g, varTable));
                        }
                        else if (v.IsProjection)
                        {
                            g.Assert(var, SP.PropertyAs, g.CreateLiteralNode(v.Name, XSD.string_.Uri));
                            //TODO check for this
                            //g.Assert(var, SP.expression, v.Projection.ToSpinRdf(query.RootGraphPattern, g, varTable));
                        }
                        else
                        {
                            g.Assert(var, SP.PropertyVarName, g.CreateLiteralNode(v.Name, XSD.string_.Uri));
                        }
                    }
                    g.Assert(vars, RDF.PropertyRest, RDF.Nil);

                    break;
                }
            }

            //Add DISTINCT/REDUCED modifiers if appropriate
            if (query.HasDistinctModifier)
            {
                switch (query.QueryType)
                {
                case SparqlQueryType.SelectAllDistinct:
                case SparqlQueryType.SelectDistinct:
                    g.Assert(root, SP.PropertyDistinct, RDFUtil.TRUE);
                    break;

                case SparqlQueryType.SelectAllReduced:
                case SparqlQueryType.SelectReduced:
                    g.Assert(root, SP.PropertyReduced, RDFUtil.TRUE);
                    break;
                }
            }

            //Add LIMIT and/or OFFSET if appropriate
            if (query.Limit > -1)
            {
                g.Assert(root, SP.PropertyLimit, query.Limit.ToLiteral(g));
            }
            if (query.Offset > 0)
            {
                g.Assert(root, SP.PropertyOffset, query.Offset.ToLiteral(g));
            }

            //Add ORDER BY if appropriate
            if (query.OrderBy != null)
            {
                g.Assert(root, SP.PropertyOrderBy, query.OrderBy.ToSpinRdf(g, varTable));
            }

            //Add GROUP BY and HAVING
            if (query.GroupBy != null)
            {
                throw new SpinException("GROUP BY clauses are not yet representable in SPIN RDF Syntax");
            }
            if (query.Having != null)
            {
                throw new SpinException("HAVING clauses are not yet representable in SPIN RDF Syntax");
            }

            return(root);
        }
예제 #7
0
 /// <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));
 }
예제 #8
0
        public BrightstarSparqlResultsType ExecuteSparql(SparqlQuery query, IStore store, TextWriter resultsWriter)
        {
            try
            {
                EnsureValidResultFormat(query);

                var dataset = MakeDataset(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;
            }
        }
 /// <summary>
 /// Converts the Algebra back to a SPARQL Query
 /// </summary>
 /// <returns></returns>
 public SparqlQuery ToQuery()
 {
     SparqlQuery q = new SparqlQuery();
     q.RootGraphPattern = this.ToGraphPattern();
     q.QueryType = SparqlQueryType.Ask;
     return q;
 }
예제 #10
0
        /// <summary>
        /// Reads query result records from the network stream.
        /// </summary>
        /// <param name="query">The original query. Used to populate table columns
        /// headers.</param>
        /// <returns>Records in DataTable.</returns>
        private DataTable ReadResults(string query)
        {
            SparqlQuery sparql = new SparqlQuery(query);
            //Get the projection column names and make table that hold result.
            SelectionTermCollection selectTerms = sparql.SelectionTerms;
            DataTable table = new DataTable();
            foreach (SelectionTerm term in selectTerms)
                table.Columns.Add(term.Name, typeof(string));

            //Read the result into table.
            for (string result = reader.ReadLine(); result != string.Empty;
                result = reader.ReadLine())
            {
                string[] fields = ResultRowParser.GetAllFields(result);

                DataRow row = table.NewRow();
                for (int i = 0; i < fields.Length; i++)
                    row[i] = fields[i];
                table.Rows.Add(row);
            }

            return table;
        }
예제 #11
0
 /// <summary>
 /// Creates a new subquery operator.
 /// </summary>
 /// <param name="q">Subquery.</param>
 public SubQuery(SparqlQuery q)
 {
     _subquery = q;
 }
예제 #12
0
        private BackgroundWorker GetWriteCsvWorker(string filename)
        {
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                using (TextWriter writer = File.CreateText(filename))
                {
                    try
                    {
                        string queryString = @"
                            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                            PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#>
                            PREFIX prov: <http://www.w3.org/ns/prov#>
                            PREFIX dces: <http://purl.org/dc/elements/1.1/>
                            PREFIX art: <http://semiodesk.com/artivity/1.0/>

                            SELECT ?activity ?agent ?influenceTime ?influenceType ?entity ?entityType ?description ?value ?bounds WHERE 
                            {
                                ?activity prov:qualifiedAssociation ?association .

                                ?association prov:agent ?agent .

                                {
                                    ?activity prov:used ?file ;
                                        prov:generated ?entity .

                                    ?entity a ?entityType ;
                                        prov:qualifiedGeneration ?generation .

                                    ?generation a ?influenceType ;
                                        prov:atTime ?influenceTime .

                                    OPTIONAL { ?generation art:hadBoundaries ?bounds . }
                                    OPTIONAL { ?generation dces:description ?description . }
                                    OPTIONAL { ?generation prov:value ?value . }
                                }
                                UNION
                                {
                                    ?editing prov:used ?file;
                                                prov:startedAtTime ?startTime ;
                                                prov:endedAtTime ?endTime .

                                    ?activity prov:startedAtTime ?time ;
                                        prov:qualifiedUsage ?usage .

                                    ?usage a ?influenceType ;
                                        prov:entity ?entity ;
                                        prov:atTime ?influenceTime .

                                    ?entity a ?entityType .

                                    FILTER(?startTime <= ?time && ?time <= ?endTime) .
                                }
                            }
                            ORDER BY DESC(?influenceTime)";

                        IModel model = Models.GetAllActivities();

                        SparqlQuery        query  = new SparqlQuery(queryString);
                        ISparqlQueryResult result = model.ExecuteQuery(query);

                        foreach (BindingSet binding in result.GetBindings())
                        {
                            writer.WriteLine(String.Join(",", binding.Values));
                        }

                        e.Result = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);

                        e.Result = false;
                    }
                }
            };

            return(worker);
        }
예제 #13
0
 protected override SparqlQuery BuildQuery(SparqlQuery query)
 {
     query.ConstructTemplate = _builder.BuildGraphPattern(Prefixes);
     return(base.BuildQuery(query));
 }
예제 #14
0
파일: Select.cs 프로젝트: ganijon/dotnetrdf
        protected override bool ValidateInternal(INode focusNode, IEnumerable <INode> valueNodes, Report report, SparqlQuery query)
        {
            var propertyShape = Shape as Shapes.Property;

            if (propertyShape != null)
            {
                BindPath(query.RootGraphPattern, propertyShape.Path.SparqlPath);
            }

            var solutions = (SparqlResultSet)focusNode.Graph.ExecuteQuery(query);

            if (solutions.IsEmpty)
            {
                return(true);
            }

            if (report is null)
            {
                return(false);
            }

            foreach (var solution in solutions)
            {
                var result = Result.Create(report.Graph);
                result.FocusNode = solution["this"];

                if (solution.TryGetBoundValue("path", out var pathValue) && pathValue.NodeType == NodeType.Uri)
                {
                    result.ResultPath = new Predicate(pathValue);
                }
                else
                {
                    if (propertyShape != null)
                    {
                        result.ResultPath = propertyShape.Path;
                    }
                }

                if (solution.HasValue("value"))
                {
                    result.ResultValue = solution["value"];
                }
                else
                {
                    result.ResultValue = focusNode;
                }

                if (solution.HasValue("message"))
                {
                    result.Message = solution["message"];
                }
                else
                {
                    result.Message = Message;
                }

                result.SourceConstraintComponent = ConstraintComponent;
                result.SourceShape      = Shape;
                result.Severity         = Shape.Severity;
                result.SourceConstraint = this;

                report.Results.Add(result);
            }

            return(false);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AsyncVirtualizingSparqlCollection{T}"/> class.
 /// </summary>
 public AsyncVirtualizingSparqlCollection(IModel model, SparqlQuery query, bool inferenceEnabled = false)
     : base(new SparqlQueryItemsProvider <T>(model, query, inferenceEnabled))
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AsyncVirtualizingSparqlCollection{T}"/> class.
 /// </summary>
 public AsyncVirtualizingSparqlCollection(IModel model, SparqlQuery query, int pageSize, bool inferenceEnabled = true)
     : base(new SparqlQueryItemsProvider <T>(model, query, inferenceEnabled), pageSize)
 {
 }
예제 #17
0
 /// <inheritdoc />
 public override SparqlResultSet ExecuteSelect(SparqlQuery sparqlQuery)
 {
     return((SparqlResultSet)_processor.ProcessQuery(sparqlQuery));
 }
예제 #18
0
 /// <summary>
 /// Creates a new subquery operator
 /// </summary>
 /// <param name="q">Subquery</param>
 public SubQuery(SparqlQuery q)
 {
     this._subquery = q;
 }
예제 #19
0
 /// <summary>
 /// Determines whether the query can be optimised for lazy evaluation
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 public override bool IsApplicable(SparqlQuery q)
 {
     return q.Limit > 0
            && !q.HasDistinctModifier
            && (q.OrderBy == null || q.IsOptimisableOrderBy)
            && q.GroupBy == null && q.Having == null
            && q.Bindings == null;
 }
예제 #20
0
        private RecipeViewModel GetRecipeByName(string name)
        {
            RecipeViewModel recipe = new RecipeViewModel();

            recipe.Name = name;
            SparqlParameterizedString query = AddPrefix();

            // Ingredients List
            query.CommandText = "SELECT ?ingre WHERE {?recipe food:hasIngredient ?ingre. FILTER( ?recipe = ingredient:" + name + ")}";
            SparqlQuery queryEx = _parser.ParseFromString(query);
            Object      result  = _graph.ExecuteQuery(queryEx);

            if (result is SparqlResultSet)
            {
                String          ingreLabel;
                SparqlResultSet rset = (SparqlResultSet)result;
                foreach (SparqlResult r in rset)
                {
                    INode n;
                    if (r.TryGetValue("ingre", out n))
                    {
                        ingreLabel = ((IUriNode)n).Uri.Segments[3];
                        recipe.Ingredients.Add(ingreLabel);
                    }
                }
            }

            // Cooking Time, Meal Type, Course Type
            query.CommandText = "SELECT ?time ?meal ?course WHERE {?recipe food:hasCookTime ?time. " +
                                "?recipe food:isRecommendedForMeal ?meal. " +
                                "?recipe food:isRecommendedForCourse ?course. " +
                                "FILTER( ?recipe = ingredient:" + name + ")}";

            queryEx = _parser.ParseFromString(query);
            result  = _graph.ExecuteQuery(queryEx);
            if (result is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)result;
                foreach (SparqlResult r in rset)
                {
                    INode n;
                    if (r.TryGetValue("time", out n))
                    {
                        recipe.CookingTime = ((ILiteralNode)n).Value;
                    }
                    if (r.TryGetValue("meal", out n))
                    {
                        recipe.MealType = ((IUriNode)n).Uri.Segments[3];
                    }
                    if (r.TryGetValue("course", out n))
                    {
                        recipe.CourseType = ((IUriNode)n).Uri.Segments[3];
                    }
                }
            }

            // Glycemic
            query.CommandText = "SELECT (SUM(?GI) as ?glycemic) " +
                                "WHERE{?recipe food:hasIngredient ?ingredient. " +
                                "?ingredient food:hasGlycemicIndex ?GI." +
                                "FILTER( ?recipe = ingredient:" + name + ")}";

            queryEx = _parser.ParseFromString(query);
            result  = _graph.ExecuteQuery(queryEx);
            if (result is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)result;
                foreach (SparqlResult r in rset)
                {
                    INode n;
                    if (r.TryGetValue("glycemic", out n))
                    {
                        recipe.Glycemic = ((ILiteralNode)n).Value;
                    }
                }
            }

            return(recipe);
        }
예제 #21
0
 /// <summary>
 /// Returns that the optimiser is applicable to all queries
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 public bool IsApplicable(SparqlQuery q)
 {
     return true;
 }
예제 #22
0
        private List <string> FindRecipes(List <string> ingreList, List <string> notIngreList, int MealType, int CourseType)
        {
            List <string> recipeList = new List <string>();

            SparqlParameterizedString query = AddPrefix();

            query.CommandText = "SELECT DISTINCT ?recipe WHERE { ?recipe rdf:type food:Recipe.";

            // Ingredient contain Query
            foreach (var item in ingreList)
            {
                query.CommandText += "?recipe food:hasIngredient ingredient:" + item + ".";
            }

            //// Ingredient NOT contain Query
            //if (notIngreList.Count > 0)
            //{
            //    query.CommandText += "FILTER ( NOT EXISTS {";
            //    foreach (var item in notIngreList)
            //    {
            //        query.CommandText += "?recipe food:hasIngredient ingredient:" + item + ".";
            //    }
            //    query.CommandText += "} )";
            //}

            // Meal Type Query
            if (MealType != 0)
            {
                string type = "";
                switch (MealType)
                {
                case (int)Meal.Breakfast: type = "Breakfast"; break;

                case (int)Meal.Lunch: type = "Lunch"; break;

                case (int)Meal.Dinner: type = "Dinner"; break;

                default:
                    break;
                }
                query.CommandText += "?recipe food:isRecommendedForMeal food:" + type + ".";
            }

            // Course Type Query
            if (CourseType != 0)
            {
                if (CourseType != (int)Course.LowSugar)
                {
                    string type = "";
                    switch (CourseType)
                    {
                    case (int)Course.Dessert: type = "Dessert"; break;

                    case (int)Course.Salad: type = "Salad"; break;

                    case (int)Course.Soup: type = "Soup"; break;

                    default:
                        break;
                    }
                    query.CommandText += "?recipe food:isRecommendedForCourse food:" + type + ".";
                }
                //else // Low Sugar Query
                //{
                //    query.CommandText += "?recipe food:hasIngredient ?ingredient. ?ingredient food:hasGlycemicIndex ?GI. FILTER (?GI <= 55)";
                //}
            }
            query.CommandText += "}";

            SparqlQuery queryEx = _parser.ParseFromString(query);
            Object      result  = _graph.ExecuteQuery(queryEx);

            if (result is SparqlResultSet)
            {
                String          recipeLabel;
                SparqlResultSet rset = (SparqlResultSet)result;
                foreach (SparqlResult r in rset)
                {
                    INode n;
                    if (r.TryGetValue("recipe", out n))
                    {
                        recipeLabel = ((IUriNode)n).Uri.Segments[3];
                        recipeList.Add(recipeLabel);
                    }
                }
            }
            if (recipeList.Count == 0)
            {
                recipeList.Add("No result!");
            }
            return(recipeList);
        }
예제 #23
0
 /// <summary>
 /// Determines whether the query can be optimised for ASK evaluation
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 public override bool IsApplicable(SparqlQuery q)
 {
     return q.QueryType == SparqlQueryType.Ask && !q.HasSolutionModifier;
 }
        public SparqlResultSet QueryFromFile(string filePath)
        {
            SparqlQuery query = _sqlQueryParser.ParseFromFile(filePath);

            return((SparqlResultSet)_processor.ProcessQuery(query));
        }
예제 #25
0
        /// <summary>
        /// Processes Query requests
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public void ProcessQueryRequest(HttpContext context)
        {
            if (this._config.QueryProcessor == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                return;
            }

            if (context.Request.HttpMethod.Equals("OPTIONS"))
            {
                //OPTIONS requests always result in the Service Description document
                IGraph svcDescrip = SparqlServiceDescriber.GetServiceDescription(context, this._config, UriFactory.Create(context.Request.Url.AbsoluteUri), ServiceDescriptionType.Query);
                HandlerHelper.SendToClient(context, svcDescrip, this._config);
                return;
            }

            //See if there has been an query submitted
            String queryText = context.Request.QueryString["query"];

            if (queryText == null || queryText.Equals(String.Empty))
            {
                if (context.Request.ContentType != null)
                {
                    if (context.Request.ContentType.Equals(MimeTypesHelper.WWWFormURLEncoded))
                    {
                        queryText = context.Request.Form["query"];
                    }
                    else if (context.Request.ContentType.Equals(MimeTypesHelper.SparqlQuery))
                    {
                        queryText = new StreamReader(context.Request.InputStream).ReadToEnd();
                    }
                }
            }

            //If no Query sent either show Query Form or give a HTTP 400 response
            if (queryText == null || queryText.Equals(String.Empty))
            {
                if (this._config.ShowQueryForm)
                {
                    this.ShowQueryForm(context);
                    return;
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return;
                }
            }

            //Get Other options associated with this query
            List <String> userDefaultGraphs = new List <String>();
            List <String> userNamedGraphs   = new List <String>();
            long          timeout           = 0;
            bool          partialResults    = this._config.DefaultPartialResults;

            //Get the Default Graph URIs (if any)
            if (context.Request.QueryString["default-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(context.Request.QueryString.GetValues("default-graph-uri"));
            }
            else if (context.Request.Form["default-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(context.Request.Form.GetValues("default-graph-uri"));
            }
            //Get the Named Graph URIs (if any)
            if (context.Request.QueryString["named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(context.Request.QueryString.GetValues("named-graph-uri"));
            }
            else if (context.Request.Form["named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(context.Request.Form.GetValues("named-graph-uri"));
            }

            //Get Timeout setting (if any)
            if (context.Request.QueryString["timeout"] != null)
            {
                if (!Int64.TryParse(context.Request.QueryString["timeout"], out timeout))
                {
                    timeout = this._config.DefaultTimeout;
                }
            }
            else if (context.Request.Form["timeout"] != null)
            {
                if (!Int64.TryParse(context.Request.Form["timeout"], out timeout))
                {
                    timeout = this._config.DefaultTimeout;
                }
            }
            //Get Partial Results Setting (if any);
            if (context.Request.QueryString["partialResults"] != null)
            {
                if (!Boolean.TryParse(context.Request.QueryString["partialResults"], out partialResults))
                {
                    partialResults = this._config.DefaultPartialResults;
                }
            }
            else if (context.Request.Form["partialResults"] != null)
            {
                if (!Boolean.TryParse(context.Request.Form["partialResults"], out partialResults))
                {
                    partialResults = this._config.DefaultPartialResults;
                }
            }

            try
            {
                //Now we're going to parse the Query
                SparqlQueryParser parser = new SparqlQueryParser(this._config.QuerySyntax);
                parser.ExpressionFactories = this._config.ExpressionFactories;
                parser.QueryOptimiser      = this._config.QueryOptimiser;
                SparqlQuery query = parser.ParseFromString(queryText);
                query.AlgebraOptimisers = this._config.AlgebraOptimisers;

                //Check whether we need to use authentication
                //If there are no user groups then no authentication is in use so we default to authenticated with no per-action authentication needed
                bool isAuth = true, requireActionAuth = false;
                if (this._config.UserGroups.Any())
                {
                    //If we have user
                    isAuth            = HandlerHelper.IsAuthenticated(context, this._config.UserGroups);
                    requireActionAuth = true;
                }
                if (!isAuth)
                {
                    return;
                }

                //Is this user allowed to make this kind of query?
                if (requireActionAuth)
                {
                    HandlerHelper.IsAuthenticated(context, this._config.UserGroups, this.GetQueryPermissionAction(query));
                }

                //Set the Default Graph URIs (if any)
                if (userDefaultGraphs.Count > 0)
                {
                    //Default Graph Uri specified by default-graph-uri parameter or Web.config settings
                    foreach (String userDefaultGraph in userDefaultGraphs)
                    {
                        if (!userDefaultGraph.Equals(String.Empty))
                        {
                            query.AddDefaultGraph(UriFactory.Create(userDefaultGraph));
                        }
                    }
                }
                else if (!this._config.DefaultGraphURI.Equals(String.Empty))
                {
                    //Only applies if the Query doesn't specify any Default Graph
                    if (!query.DefaultGraphs.Any())
                    {
                        query.AddDefaultGraph(UriFactory.Create(this._config.DefaultGraphURI));
                    }
                }

                //Set the Named Graph URIs (if any)
                if (userNamedGraphs.Count > 0)
                {
                    foreach (String userNamedGraph in userNamedGraphs)
                    {
                        if (!userNamedGraph.Equals(String.Empty))
                        {
                            query.AddNamedGraph(UriFactory.Create(userNamedGraph));
                        }
                    }
                }

                //Set Timeout setting
                if (timeout > 0)
                {
                    query.Timeout = timeout;
                }
                else
                {
                    query.Timeout = this._config.DefaultTimeout;
                }

                //Set Partial Results Setting
                query.PartialResultsOnTimeout = partialResults;

                //Set Describe Algorithm
                query.Describer = this._config.DescribeAlgorithm;

                //Now we can finally make the query and return the results
                Object result = this.ProcessQuery(query);
                this.ProcessQueryResults(context, result);

                //Update the Cache as the request may have changed the endpoint
                this.UpdateConfig(context);
            }
            catch (RdfParseException parseEx)
            {
                HandleQueryErrors(context, "Parsing Error", queryText, parseEx, (int)HttpStatusCode.BadRequest);
            }
            catch (RdfQueryTimeoutException timeoutEx)
            {
                HandleQueryErrors(context, "Query Timeout Error", queryText, timeoutEx);
            }
            catch (RdfQueryException queryEx)
            {
                HandleQueryErrors(context, "Query Error", queryText, queryEx);
            }
            catch (RdfWriterSelectionException writerSelEx)
            {
                HandleQueryErrors(context, "Output Selection Error", queryText, writerSelEx, (int)HttpStatusCode.NotAcceptable);
            }
            catch (RdfException rdfEx)
            {
                HandleQueryErrors(context, "RDF Error", queryText, rdfEx);
            }
            catch (Exception ex)
            {
                HandleQueryErrors(context, "Error", queryText, ex);
            }
        }
예제 #26
0
 // TODO: Test
 public Reader(IGraph g, SparqlQuery query)
     : this(((SparqlResultSet)g.ExecuteQuery(Validate(query))).Select(r => r["root"]))
 {
 }
예제 #27
0
        /// <summary>
        /// Processes a SPARQL Query Request
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public void ProcessRequest(HttpContext context)
        {
            this._config = this.LoadConfig(context);

            //Add our Standard Headers
            HandlerHelper.AddStandardHeaders(context, this._config);

            if (context.Request.HttpMethod.Equals("OPTIONS"))
            {
                //OPTIONS requests always result in the Service Description document
                IGraph svcDescrip = SparqlServiceDescriber.GetServiceDescription(context, this._config, new Uri(context.Request.Url.AbsoluteUri));
                HandlerHelper.SendToClient(context, svcDescrip, this._config);
                return;
            }

            //See if there has been an query submitted
            String queryText = context.Request.QueryString["query"];

            if (queryText == null || queryText.Equals(String.Empty))
            {
                queryText = context.Request.Form["query"];
            }

            //If no Query sent either show Query Form or give a HTTP 400 response
            if (queryText == null || queryText.Equals(String.Empty))
            {
                //If there is no Query we may return the SPARQL Service Description where appropriate
                try
                {
                    //If we might show the Query Form only show the Description if the selected writer is
                    //not a HTML writer
                    MimeTypeDefinition definition = MimeTypesHelper.GetDefinitions(HandlerHelper.GetAcceptTypes(context)).FirstOrDefault(d => d.CanWriteRdf);
                    if (definition != null)
                    {
                        IRdfWriter writer = definition.GetRdfWriter();
                        if (!this._config.ShowQueryForm || !(writer is IHtmlWriter))
                        {
                            //If not a HTML Writer selected OR not showing Query Form then show the Service Description Graph
                            //unless an error occurs creating it
                            IGraph serviceDescrip = SparqlServiceDescriber.GetServiceDescription(context, this._config, new Uri(context.Request.Url.AbsoluteUri));
                            context.Response.ContentType     = definition.CanonicalMimeType;
                            context.Response.ContentEncoding = definition.Encoding;
                            writer.Save(serviceDescrip, new StreamWriter(context.Response.OutputStream, definition.Encoding));
                            return;
                        }
                    }
                }
                catch
                {
                    //Ignore Exceptions - we'll just show the Query Form or return a 400 Bad Request instead
                }

                //If a Writer can't be selected then we'll either show the Query Form or return a 400 Bad Request
                if (this._config.ShowQueryForm)
                {
                    this.ShowQueryForm(context);
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                }
                return;
            }

            //Get Other options associated with this query
            List <String> userDefaultGraphs = new List <String>();
            List <String> userNamedGraphs   = new List <String>();
            long          timeout           = 0;
            bool          partialResults    = this._config.DefaultPartialResults;

            //Get the Default Graph URIs (if any)
            if (context.Request.QueryString["default-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(context.Request.QueryString.GetValues("default-graph-uri"));
            }
            else if (context.Request.Form["default-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(context.Request.Form.GetValues("default-graph-uri"));
            }
            //Get the Named Graph URIs (if any)
            if (context.Request.QueryString["named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(context.Request.QueryString.GetValues("named-graph-uri"));
            }
            else if (context.Request.Form["named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(context.Request.Form.GetValues("named-graph-uri"));
            }

            //Get Timeout setting (if any)
            if (context.Request.QueryString["timeout"] != null)
            {
                if (!Int64.TryParse(context.Request.QueryString["timeout"], out timeout))
                {
                    timeout = this._config.DefaultTimeout;
                }
            }
            else if (context.Request.Form["timeout"] != null)
            {
                if (!Int64.TryParse(context.Request.Form["timeout"], out timeout))
                {
                    timeout = this._config.DefaultTimeout;
                }
            }
            //Get Partial Results Setting (if any);
            if (context.Request.QueryString["partialResults"] != null)
            {
                if (!Boolean.TryParse(context.Request.QueryString["partialResults"], out partialResults))
                {
                    partialResults = this._config.DefaultPartialResults;
                }
            }
            else if (context.Request.Form["partialResults"] != null)
            {
                if (!Boolean.TryParse(context.Request.Form["partialResults"], out partialResults))
                {
                    partialResults = this._config.DefaultPartialResults;
                }
            }

            try
            {
                //Now we're going to parse the Query
                SparqlQueryParser parser = new SparqlQueryParser(this._config.Syntax);
                parser.ExpressionFactories = this._config.ExpressionFactories;
                parser.QueryOptimiser      = this._config.QueryOptimiser;
                SparqlQuery query = parser.ParseFromString(queryText);
                query.AlgebraOptimisers = this._config.AlgebraOptimisers;

                //Check whether we need to use authentication
                //If there are no user groups then no authentication is in use so we default to authenticated with no per-action authentication needed
                bool isAuth = true, requireActionAuth = false;
                if (this._config.UserGroups.Any())
                {
                    //If we have user
                    isAuth            = HandlerHelper.IsAuthenticated(context, this._config.UserGroups);
                    requireActionAuth = true;
                }
                if (!isAuth)
                {
                    return;
                }

                //Is this user allowed to make this kind of query?
                if (requireActionAuth)
                {
                    HandlerHelper.IsAuthenticated(context, this._config.UserGroups, this.GetPermissionAction(query));
                }

                //Set the Default Graph URIs (if any)
                if (userDefaultGraphs.Count > 0)
                {
                    //Default Graph Uri specified by default-graph-uri parameter or Web.config settings
                    foreach (String userDefaultGraph in userDefaultGraphs)
                    {
                        if (!userDefaultGraph.Equals(String.Empty))
                        {
                            query.AddDefaultGraph(new Uri(userDefaultGraph));
                        }
                    }
                }
                else if (!this._config.DefaultGraphURI.Equals(String.Empty))
                {
                    //Only applies if the Query doesn't specify any Default Graph
                    if (!query.DefaultGraphs.Any())
                    {
                        query.AddDefaultGraph(new Uri(this._config.DefaultGraphURI));
                    }
                }

                //Set the Named Graph URIs (if any)
                if (userNamedGraphs.Count > 0)
                {
                    foreach (String userNamedGraph in userNamedGraphs)
                    {
                        if (!userNamedGraph.Equals(String.Empty))
                        {
                            query.AddNamedGraph(new Uri(userNamedGraph));
                        }
                    }
                }

                //Set Timeout setting
                if (timeout > 0)
                {
                    query.Timeout = timeout;
                }
                else
                {
                    query.Timeout = this._config.DefaultTimeout;
                }

                //Set Partial Results Setting
                query.PartialResultsOnTimeout = partialResults;

                //Set Describe Algorithm
                query.Describer = this._config.DescribeAlgorithm;

                //Now we can finally make the query and return the results
                Object result = this.ProcessQuery(query);
                this.ProcessResults(context, result);

                //Update the Cache as the request may have changed the endpoint
                this.UpdateConfig(context);
            }
            catch (RdfParseException parseEx)
            {
                HandleErrors(context, "Parsing Error", queryText, parseEx, (int)HttpStatusCode.BadRequest);
            }
            catch (RdfQueryTimeoutException timeoutEx)
            {
                HandleErrors(context, "Query Timeout Error", queryText, timeoutEx);
            }
            catch (RdfQueryException queryEx)
            {
                HandleErrors(context, "Update Error", queryText, queryEx);
            }
            catch (RdfWriterSelectionException writerSelEx)
            {
                HandleErrors(context, "Output Selection Error", queryText, writerSelEx, (int)HttpStatusCode.NotAcceptable);
            }
            catch (RdfException rdfEx)
            {
                HandleErrors(context, "RDF Error", queryText, rdfEx);
            }
            catch (Exception ex)
            {
                HandleErrors(context, "Error", queryText, ex);
            }
        }
예제 #28
0
 private static SparqlQuery Validate(SparqlQuery query)
 {
     // TODO: Validate
     return(query);
 }
예제 #29
0
        /// <summary>
        /// Evaluates the Command in the given Context
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        public override void Evaluate(SparqlUpdateEvaluationContext context)
        {
            bool defGraphOk = false;
            bool datasetOk  = false;

            try
            {
                // If there is a WITH clause and no matching graph, and the delete pattern doesn't contain child graph patterns then there is nothing to do
                if (_graphUri != null && !context.Data.HasGraph(_graphUri) && !_deletePattern.HasChildGraphPatterns)
                {
                    return;
                }

                // First evaluate the WHERE pattern to get the affected bindings
                ISparqlAlgebra where = _wherePattern.ToAlgebra();
                if (context.Commands != null)
                {
                    where = context.Commands.ApplyAlgebraOptimisers(where);
                }

                // Set Active Graph for the WHERE based upon the WITH clause
                // Don't bother if there are USING URIs as these would override any Active Graph we set here
                // so we can save ourselves the effort of doing this
                if (!UsingUris.Any())
                {
                    if (_graphUri != null)
                    {
                        context.Data.SetActiveGraph(_graphUri);
                        defGraphOk = true;
                    }
                    else
                    {
                        context.Data.SetActiveGraph((Uri)null);
                        defGraphOk = true;
                    }
                }

                // We need to make a dummy SparqlQuery object since if the Command has used any
                // USING/USING NAMEDs along with GRAPH clauses then the algebra needs to have the
                // URIs available to it which it gets from the Query property of the Context
                // object
                SparqlQuery query = new SparqlQuery();
                foreach (Uri u in UsingUris)
                {
                    query.AddDefaultGraph(u);
                }
                foreach (Uri u in UsingNamedUris)
                {
                    query.AddNamedGraph(u);
                }
                SparqlEvaluationContext queryContext = new SparqlEvaluationContext(query, context.Data, context.QueryProcessor);
                if (UsingUris.Any())
                {
                    // If there are USING URIs set the Active Graph to be formed of the Graphs with those URIs
                    context.Data.SetActiveGraph(_usingUris);
                    datasetOk = true;
                }
                BaseMultiset results = queryContext.Evaluate(where);
                if (results is IdentityMultiset)
                {
                    results = new SingletonMultiset(results.Variables);
                }
                if (UsingUris.Any())
                {
                    // If there are USING URIs reset the Active Graph afterwards
                    // Also flag the dataset as no longer being OK as this flag is used in the finally
                    // block to determine whether the Active Graph needs resetting which it may do if the
                    // evaluation of the
                    context.Data.ResetActiveGraph();
                    datasetOk = false;
                }

                // Reset Active Graph for the WHERE
                if (defGraphOk)
                {
                    context.Data.ResetActiveGraph();
                    defGraphOk = false;
                }

                // Get the Graph from which we are deleting
                IGraph g = context.Data.HasGraph(_graphUri) ? context.Data.GetModifiableGraph(_graphUri) : null;

                // Delete the Triples for each Solution
                foreach (ISet s in results.Sets)
                {
                    List <Triple> deletedTriples = new List <Triple>();

                    if (g != null)
                    {
                        // Triples from raw Triple Patterns
                        try
                        {
                            ConstructContext constructContext = new ConstructContext(g, s, true);
                            foreach (IConstructTriplePattern p in _deletePattern.TriplePatterns
                                     .OfType <IConstructTriplePattern>())
                            {
                                try
                                {
                                    deletedTriples.Add(p.Construct(constructContext));
                                }
                                catch (RdfQueryException)
                                {
                                    // If we get an error here then we couldn't construct a specific Triple
                                    // so we continue anyway
                                }
                            }

                            g.Retract(deletedTriples);
                        }
                        catch (RdfQueryException)
                        {
                            // If we throw an error this means we couldn't construct for this solution so the
                            // solution is ignored this graph
                        }
                    }

                    // Triples from GRAPH clauses
                    foreach (GraphPattern gp in _deletePattern.ChildGraphPatterns)
                    {
                        deletedTriples.Clear();
                        try
                        {
                            String graphUri;
                            switch (gp.GraphSpecifier.TokenType)
                            {
                            case Token.URI:
                                graphUri = gp.GraphSpecifier.Value;
                                break;

                            case Token.VARIABLE:
                                String graphVar = gp.GraphSpecifier.Value.Substring(1);
                                if (s.ContainsVariable(graphVar))
                                {
                                    INode temp = s[graphVar];
                                    if (temp == null)
                                    {
                                        // If the Variable is not bound then skip
                                        continue;
                                    }
                                    else if (temp.NodeType == NodeType.Uri)
                                    {
                                        graphUri = temp.ToSafeString();
                                    }
                                    else
                                    {
                                        // If the Variable is not bound to a URI then skip
                                        continue;
                                    }
                                }
                                else
                                {
                                    // If the Variable is not bound for this solution then skip
                                    continue;
                                }
                                break;

                            default:
                                // Any other Graph Specifier we have to ignore this solution
                                continue;
                            }

                            // If the Dataset doesn't contain the Graph then no need to do the Deletions
                            if (!context.Data.HasGraph(UriFactory.Create(graphUri)))
                            {
                                continue;
                            }

                            // Do the actual Deletions
                            IGraph           h = context.Data.GetModifiableGraph(UriFactory.Create(graphUri));
                            ConstructContext constructContext = new ConstructContext(h, s, true);
                            foreach (IConstructTriplePattern p in gp.TriplePatterns.OfType <IConstructTriplePattern>())
                            {
                                try
                                {
                                    deletedTriples.Add(p.Construct(constructContext));
                                }
                                catch (RdfQueryException)
                                {
                                    // If we get an error here then we couldn't construct a specific
                                    // triple so we continue anyway
                                }
                            }
                            h.Retract(deletedTriples);
                        }
                        catch (RdfQueryException)
                        {
                            // If we get an error here this means we couldn't construct for this solution so the
                            // solution is ignored for this graph
                        }
                    }
                }
            }
            finally
            {
                // If the Dataset was set and an error occurred in doing the WHERE clause then
                // we'll need to Reset the Active Graph
                if (datasetOk)
                {
                    context.Data.ResetActiveGraph();
                }
                if (defGraphOk)
                {
                    context.Data.ResetActiveGraph();
                }
            }
        }
예제 #30
0
        private void BuildRootGraphPattern(SparqlQuery query)
        {
            var rootGraphPattern = RootGraphPatternBuilder.BuildGraphPattern(Prefixes);

            query.RootGraphPattern = rootGraphPattern;
        }
예제 #31
0
 /// <summary>
 /// Determines whether the query can be optimised for ASK evaluation
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 public override bool IsApplicable(SparqlQuery q)
 {
     return(q.QueryType == SparqlQueryType.Ask && !q.HasSolutionModifier);
 }
예제 #32
0
        /// <summary>
        /// Runs the task
        /// </summary>
        /// <returns></returns>
        protected override object RunTaskInternal()
        {
            try
            {
                //Firstly try and parse the Query
                this._q = this._parser.ParseFromString(this._query);
            }
            catch
            {
                this.Information = "Query is not valid SPARQL 1.0/1.1 - will attempt to evaluate it but underlying store may reject the query...";
            }

            if (this._q != null)
            {
                //Then apply it to the Manager using the GenericQueryProcessor
                try
                {
                    //Check that paging can be used if it was enabled
                    if (this._usePaging)
                    {
                        if (this._q.Limit >= 0 || this._q.Offset > 0)
                        {
                            throw new RdfQueryException("Cannot apply query paging when the SPARQL Query already contains an explicit LIMIT and/or OFFSET clause");
                        }
                        else if (this._q.QueryType == SparqlQueryType.Ask)
                        {
                            throw new RdfQueryException("Cannot apply query paging to an ASK Query");
                        }
                    }

                    int      offset    = 0;
                    TimeSpan totalTime = TimeSpan.Zero;

                    switch (this._q.QueryType)
                    {
                    case SparqlQueryType.Ask:
                        SparqlResultSet blnResult = this._processor.ProcessQuery(this._q) as SparqlResultSet;
                        if (blnResult == null)
                        {
                            throw new RdfQueryException("Store did not return a SPARQL Result Set for the ASK query as was expected");
                        }
                        return(blnResult);

                    case SparqlQueryType.Construct:
                    case SparqlQueryType.Describe:
                    case SparqlQueryType.DescribeAll:
                        Graph g = new Graph();
                        g.NamespaceMap.Import(this._q.NamespaceMap);

                        do
                        {
                            if (this._usePaging)
                            {
                                this._q.Limit  = this._pageSize;
                                this._q.Offset = offset;
                            }
                            Object result = this._processor.ProcessQuery(this._q);
                            totalTime += this._q.QueryExecutionTime.Value;

                            if (!(result is IGraph))
                            {
                                throw new RdfQueryException("SPARQL Query did not return a RDF Graph as expected");
                            }
                            IGraph temp = (IGraph)result;

                            //If no further results can halt
                            if (temp.Triples.Count == 0)
                            {
                                break;
                            }
                            offset += this._pageSize;

                            //Merge the partial result into the final result
                            g.Merge(temp);
                        } while (this._usePaging);

                        this.Information = "Query Completed OK (Took " + totalTime.ToString() + ")";
                        return(g);

                    case SparqlQueryType.Select:
                    case SparqlQueryType.SelectAll:
                    case SparqlQueryType.SelectAllDistinct:
                    case SparqlQueryType.SelectAllReduced:
                    case SparqlQueryType.SelectDistinct:
                    case SparqlQueryType.SelectReduced:
                        SparqlResultSet  results = new SparqlResultSet();
                        ResultSetHandler handler = new ResultSetHandler(results);
                        try
                        {
                            handler.StartResults();

                            do
                            {
                                if (this._usePaging)
                                {
                                    this._q.Limit  = this._pageSize;
                                    this._q.Offset = offset;
                                }
                                Object result = this._processor.ProcessQuery(this._q);
                                totalTime += this._q.QueryExecutionTime.Value;

                                if (!(result is SparqlResultSet))
                                {
                                    throw new RdfQueryException("SPARQL Query did not return a SPARQL Result Set as expected");
                                }
                                SparqlResultSet rset = (SparqlResultSet)result;
                                foreach (String var in rset.Variables)
                                {
                                    handler.HandleVariable(var);
                                }

                                //If no further results can halt
                                if (rset.Count == 0)
                                {
                                    break;
                                }
                                offset += this._pageSize;

                                //Merge the partial result into the final result
                                foreach (SparqlResult r in rset)
                                {
                                    handler.HandleResult(r);
                                }
                            } while (this._usePaging);

                            handler.EndResults(true);
                        }
                        catch
                        {
                            handler.EndResults(false);
                            throw;
                        }
                        this.Information = "Query Completed OK (Took " + totalTime.ToString() + ")";
                        return(results);

                    default:
                        throw new RdfQueryException("Cannot evaluate an unknown query type");
                    }
                }
                catch
                {
                    //Try and show the execution time if possible
                    try
                    {
                        this.Information = "Query Failed (Took " + this._q.QueryExecutionTime.Value.ToString() + ")";
                    }
                    catch
                    {
                        this.Information = "Query Failed";
                    }
                    throw;
                }
            }
            else
            {
                DateTime start = DateTime.Now;
                try
                {
                    if (this._usePaging)
                    {
                        throw new RdfQueryException("Cannot apply paging to a Query that we cannot parse as a valid SPARQL 1.0/1.1 query");
                    }
                    Object results = this._manager.Query(this._query);
                    this.Information = "Query Completed OK (Took " + (DateTime.Now - start).ToString() + ")";
                    return(results);
                }
                catch
                {
                    //Try and show the execution time if possible
                    try
                    {
                        this.Information = "Query Failed (Took " + (DateTime.Now - start).ToString() + ")";
                    }
                    catch
                    {
                        this.Information = "Query Failed";
                    }
                    throw;
                }
            }
        }
예제 #33
0
        public void SparqlOrderByComplexLazyPerformance()
        {
            String query = "SELECT * WHERE { ?s ?p ?o . } ORDER BY ?s DESC(?p) LIMIT 5";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

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

            SparqlQueryParser parser = new SparqlQueryParser();

            //First do with Optimisation
            Stopwatch   timer = new Stopwatch();
            SparqlQuery q     = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            timer.Start();
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));
            Object results = processor.ProcessQuery(q);

            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Optimised");
            timer.Reset();
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }

            //Then do without optimisation
            Options.AlgebraOptimisation = false;
            timer.Start();
            results = processor.ProcessQuery(q);
            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Unoptimised");
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
            Options.AlgebraOptimisation = true;
        }
예제 #34
0
        /// <summary>
        /// Formats a Query in nicely formatted SPARQL syntax
        /// </summary>
        /// <param name="query">SPARQL Query</param>
        /// <returns></returns>
        public virtual String Format(SparqlQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("Cannot format a null SPARQL Query as a String");
            }

            try
            {
                this._tempBaseUri = query.BaseUri;
                StringBuilder output = new StringBuilder();

                //Base and Prefix Declarations if not a sub-query
                if (!query.IsSubQuery)
                {
                    if (query.BaseUri != null)
                    {
                        output.AppendLine("BASE <" + this.FormatUri(query.BaseUri.ToString()) + ">");
                    }
                    foreach (String prefix in this._qnameMapper.Prefixes)
                    {
                        output.AppendLine("PREFIX " + prefix + ": <" + this.FormatUri(this._qnameMapper.GetNamespaceUri(prefix).ToString()) + ">");
                    }

                    //Use a Blank Line to separate Prologue from Query where necessary
                    if (query.BaseUri != null || this._qnameMapper.Prefixes.Any())
                    {
                        output.AppendLine();
                    }
                }

                //Next up is the Query Verb
                switch (query.QueryType)
                {
                case SparqlQueryType.Ask:
                    output.Append("ASK ");
                    break;

                case SparqlQueryType.Construct:
                    output.AppendLine("CONSTRUCT");
                    //Add in the Construct Pattern
                    output.AppendLine(this.Format(query.ConstructTemplate));
                    break;

                case SparqlQueryType.Describe:
                    output.Append("DESCRIBE ");
                    output.AppendLine(this.FormatDescribeVariablesList(query));
                    break;

                case SparqlQueryType.DescribeAll:
                    output.Append("DESCRIBE * ");
                    break;

                case SparqlQueryType.Select:
                    output.Append("SELECT ");
                    output.AppendLine(this.FormatVariablesList(query.Variables));
                    break;

                case SparqlQueryType.SelectAll:
                    output.AppendLine("SELECT *");
                    break;

                case SparqlQueryType.SelectAllDistinct:
                    output.AppendLine("SELECT DISTINCT *");
                    break;

                case SparqlQueryType.SelectAllReduced:
                    output.AppendLine("SELECT REDUCED *");
                    break;

                case SparqlQueryType.SelectDistinct:
                    output.Append("SELECT DISTINCT ");
                    output.AppendLine(this.FormatVariablesList(query.Variables));
                    break;

                case SparqlQueryType.SelectReduced:
                    output.Append("SELECT REDUCED ");
                    output.AppendLine(this.FormatVariablesList(query.Variables));
                    break;

                default:
                    throw new RdfOutputException("Cannot Format an Unknown Query Type");
                }

                //Then add in FROM and FROM NAMED if not a sub-query
                if (!query.IsSubQuery)
                {
                    foreach (Uri u in query.DefaultGraphs)
                    {
                        output.AppendLine("FROM <" + this.FormatUri(u) + ">");
                    }
                    foreach (Uri u in query.NamedGraphs)
                    {
                        output.AppendLine("FROM NAMED <" + this.FormatUri(u) + ">");
                    }
                }

                //Then the WHERE clause (unless there isn't one)
                if (query.RootGraphPattern == null)
                {
                    if (query.QueryType != SparqlQueryType.Describe)
                    {
                        throw new RdfOutputException("Cannot Format a SPARQL Query as it has no Graph Pattern for the WHERE clause and is not a DESCRIBE query");
                    }
                }
                else
                {
                    if (query.RootGraphPattern.IsEmpty)
                    {
                        output.AppendLine("WHERE { }");
                    }
                    else
                    {
                        output.AppendLine("WHERE");
                        if (query.RootGraphPattern.HasModifier)
                        {
                            output.AppendLine("{");
                        }
                        output.AppendLine(this.Format(query.RootGraphPattern));
                    }
                }

                //Then a GROUP BY
                if (query.GroupBy != null)
                {
                    output.Append("GROUP BY ");
                    output.AppendLine(this.FormatGroupBy(query.GroupBy));
                }

                //Then a HAVING
                if (query.Having != null)
                {
                    output.Append("HAVING ");
                    output.Append('(');
                    output.Append(this.FormatExpression(query.Having.Expression));
                    output.AppendLine(")");
                }

                //Then ORDER BY
                if (query.OrderBy != null)
                {
                    output.Append("ORDER BY ");
                    output.AppendLine(this.FormatOrderBy(query.OrderBy));
                }

                //Then LIMIT and OFFSET
                if (query.Limit >= 0)
                {
                    output.AppendLine("LIMIT " + query.Limit);
                }
                if (query.Offset > 0)
                {
                    output.AppendLine("OFFSET " + query.Offset);
                }

                //Finally BINDINGS
                if (query.Bindings != null)
                {
                    output.Append("BINDINGS ");
                    foreach (String var in query.Bindings.Variables)
                    {
                        output.Append("?" + var);
                        output.Append(' ');
                    }
                    if (query.Bindings.Variables.Any())
                    {
                        output.AppendLine();
                    }
                    output.Append('{');
                    bool multipleTuples = query.Bindings.Tuples.Count() > 1;
                    if (multipleTuples)
                    {
                        output.AppendLine();
                    }
                    foreach (BindingTuple tuple in query.Bindings.Tuples)
                    {
                        if (tuple.IsEmpty)
                        {
                            if (multipleTuples)
                            {
                                output.AppendLineIndented("()", 2);
                            }
                            else
                            {
                                output.Append(" () ");
                            }
                            continue;
                        }

                        if (multipleTuples)
                        {
                            output.AppendIndented("(", 2);
                        }
                        else
                        {
                            output.Append("(");
                        }
                        foreach (String var in query.Bindings.Variables)
                        {
                            output.Append(' ');
                            if (tuple[var] == null)
                            {
                                output.AppendLine(SparqlSpecsHelper.SparqlKeywordUndef);
                            }
                            else
                            {
                                output.Append(this.Format(tuple[var], null));
                            }
                        }
                        if (multipleTuples)
                        {
                            output.AppendLine(")");
                        }
                        else
                        {
                            output.Append(')');
                        }
                    }
                    output.AppendLine("}");
                }

                return(output.ToString());
            }
            finally
            {
                this._tempBaseUri = null;
            }
        }
예제 #35
0
 /// <summary>
 /// Returns that this optimiser is applicable to all queries.
 /// </summary>
 /// <param name="q">Query.</param>
 /// <returns></returns>
 public bool IsApplicable(SparqlQuery q)
 {
     return(true);
 }
예제 #36
0
        /// <summary>
        /// Formats the Variable/QName/URI for a SPARQL DESCRIBE Query
        /// </summary>
        /// <param name="q">SPARQL Query</param>
        /// <returns></returns>
        protected virtual String FormatDescribeVariablesList(SparqlQuery q)
        {
            StringBuilder output = new StringBuilder();

            List <IToken> tokenList = q.DescribeVariables.ToList();

            int onLine = 0;

            for (int i = 0; i < tokenList.Count; i++)
            {
                IToken t = tokenList[i];

                switch (t.TokenType)
                {
                case Token.VARIABLE:
                    output.Append(t.Value);
                    onLine++;
                    break;

                case Token.URI:
                    output.Append('<');
                    output.Append(this.FormatUri(t.Value));
                    output.Append('>');
                    onLine += 3;
                    break;

                case Token.QNAME:
                    //If the QName has the same Namespace URI in this Formatter as in the Query then format
                    //as a QName otherwise expand to a full URI
                    String prefix = t.Value.Substring(0, t.Value.IndexOf(':'));
                    if (this._qnameMapper.HasNamespace(prefix) && q.NamespaceMap.GetNamespaceUri(prefix).ToString().Equals(this._qnameMapper.GetNamespaceUri(prefix).ToString()))
                    {
                        output.AppendLine(t.Value);
                        onLine += 2;
                    }
                    else if (q.NamespaceMap.HasNamespace(prefix))
                    {
                        output.Append('<');
                        output.Append(this.FormatUri(Tools.ResolveQName(t.Value, q.NamespaceMap, q.BaseUri)));
                        output.Append('>');
                        onLine += 3;
                    }
                    else
                    {
                        throw new RdfOutputException("Unable to Format the DESCRIBE variables list since one of the Variables is the QName '" + t.Value + "' which cannot be resolved using the Namespace Map of the Query");
                    }

                    break;
                }

                //Maximum of 6 things per line (URIs worth 3 and QNames worth 2)
                if (onLine >= 6 && i < tokenList.Count - 1)
                {
                    output.AppendLine();
                }
                else if (i < tokenList.Count - 1)
                {
                    output.Append(' ');
                }
            }

            return(output.ToString());
        }
예제 #37
0
 /// <summary>
 /// Determines whether the query can be optimised for ASK evaluation
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 public override bool IsApplicable(SparqlQuery q)
 {
     return q.QueryType == SparqlQueryType.Ask;
 }
 /// <summary>
 /// Returns false because this optimiser is never globally applicable
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 public bool IsApplicable(SparqlQuery q)
 {
     return false;
 }
예제 #39
0
 /// <summary>
 /// Gets the value of the function in the given Evaluation Context for the given Binding ID
 /// </summary>
 /// <param name="context">Evaluation Context</param>
 /// <param name="bindingID">Binding ID</param>
 /// <returns>
 /// Returns a constant Literal Node which is a Date Time typed Literal
 /// </returns>
 public IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
 {
     if (this._currQuery == null)
     {
         this._currQuery = context.Query;
     }
     if (this._node == null || !ReferenceEquals(this._currQuery, context.Query))
     {
         this._node = new DateTimeNode(null, DateTime.Now);
     }
     return this._node;
 }
예제 #40
0
파일: Filter.cs 프로젝트: jmahmud/RDFer
 /// <summary>
 /// Converts the Algebra back to a SPARQL Query
 /// </summary>
 /// <returns></returns>
 public SparqlQuery ToQuery()
 {
     SparqlQuery q = new SparqlQuery();
     q.RootGraphPattern = this.ToGraphPattern();
     q.Optimise();
     return q;
 }
예제 #41
0
        private void QueryInternal(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String query, String servicePath)
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            try
            {
                //Single Query parameter
                Dictionary <String, String> ps = new Dictionary <string, string>();
                ps.Add("query", query);

                //Parse the query locally to validate it and so we can decide what to do
                //when we receive the Response more easily as we'll know the query type
                //This also saves us wasting a HttpWebRequest on a malformed query
                SparqlQueryParser qparser = new SparqlQueryParser();
                SparqlQuery       q       = qparser.ParseFromString(query);

                //Get the Request
                request        = this.CreateRequest(servicePath, ps);
                request.Method = "GET";

                switch (q.QueryType)
                {
                case SparqlQueryType.Ask:
                case SparqlQueryType.Select:
                case SparqlQueryType.SelectAll:
                case SparqlQueryType.SelectAllDistinct:
                case SparqlQueryType.SelectAllReduced:
                case SparqlQueryType.SelectDistinct:
                case SparqlQueryType.SelectReduced:
                    //Some kind of Sparql Result Set
                    request.Accept = MimeTypesHelper.HttpSparqlAcceptHeader;

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

                    using (response = (HttpWebResponse)request.GetResponse())
                    {
#if DEBUG
                        if (Options.HttpDebugging)
                        {
                            Tools.HttpDebugResponse(response);
                        }
#endif
                        ISparqlResultsReader resultsParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                        resultsParser.Load(resultsHandler, new StreamReader(response.GetResponseStream()));
                        response.Close();
                    }
                    break;

                case SparqlQueryType.Construct:
                case SparqlQueryType.Describe:
                case SparqlQueryType.DescribeAll:
                    //Some kind of Graph
                    //HACK: Have to send only RDF/XML as the accept header due to a known issue with Talis Platform
                    request.Accept = MimeTypesHelper.RdfXml[0];    //MimeTypesHelper.HttpAcceptHeader;

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

                    using (response = (HttpWebResponse)request.GetResponse())
                    {
#if DEBUG
                        if (Options.HttpDebugging)
                        {
                            Tools.HttpDebugResponse(response);
                        }
#endif
                        IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                        parser.Load(rdfHandler, new StreamReader(response.GetResponseStream()));
                        response.Close();
                    }
                    break;

                default:
                    //Error
                    throw new RdfQueryException("Unknown Query Type was used, unable to determine how to process the response from Talis");
                }
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    //Got a Response so we can analyse the Response Code
                    response = (HttpWebResponse)webEx.Response;
                    int code = (int)response.StatusCode;
                    throw Error(code, webEx);
                }
                //Didn't get a Response
                throw;
            }
        }
 /// <summary>
 /// Converts the Algebra back to a SPARQL Query
 /// </summary>
 /// <returns></returns>
 public SparqlQuery ToQuery()
 {
     SparqlQuery q = new SparqlQuery();
     q.RootGraphPattern = this.ToGraphPattern();
     q.AddVariable(this._graphVar, true);
     q.Optimise();
     return q;
 }
예제 #43
0
 /// <summary>
 /// Determines whether the Optimiser can be applied to a given Query
 /// </summary>
 /// <param name="q">Query</param>
 /// <returns></returns>
 public abstract bool IsApplicable(SparqlQuery q);
예제 #44
0
파일: SubQuery.cs 프로젝트: jmahmud/RDFer
 /// <summary>
 /// Creates a new subquery operator
 /// </summary>
 /// <param name="q">Subquery</param>
 public SubQuery(SparqlQuery q)
 {
     this._subquery = q;
 }
예제 #45
0
 private SparqlResultSet Run(SparqlQuery.SparqlClasses.Query.SparqlQuery queryContext)
 {
     return queryContext.Run();
 }
예제 #46
0
 /// <summary>
 /// Determines whether the Optimiser can be applied to a given Query.
 /// </summary>
 /// <param name="q">Query.</param>
 /// <returns></returns>
 public abstract bool IsApplicable(SparqlQuery q);