Example #1
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>
 public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
 {
     INode temp = this._expr.Evaluate(context, bindingID);
     if (temp != null)
     {
         if (temp.NodeType == NodeType.Uri)
         {
             IUriNode u = (IUriNode)temp;
             if (!u.Uri.Fragment.Equals(String.Empty))
             {
                 return new StringNode(null, u.Uri.Fragment.Substring(1));
             }
             else
             {
     #if SILVERLIGHT
                 return new StringNode(null, u.Uri.Segments().Last());
     #else
                 return new StringNode(null, u.Uri.Segments.Last());
     #endif
             }
         }
         else
         {
             throw new RdfQueryException("Cannot find the Local Name for a non-URI Node");
         }
     }
     else
     {
         throw new RdfQueryException("Cannot find the Local Name for a null");
     }
 }
        /// <summary>
        /// Evaluates the Select Distinct Graphs optimisation
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <returns></returns>
        public BaseMultiset Evaluate(SparqlEvaluationContext context)
        {
            context.OutputMultiset = new Multiset();
            String var;
            if (context.Query != null)
            {
                var = context.Query.Variables.First(v => v.IsResultVariable).Name;
            }
            else
            {
                var = this._graphVar;
            }

            foreach (Uri graphUri in context.Data.GraphUris)
            {
                Set s = new Set();
                if (graphUri == null)
                {
                    s.Add(var, null);
                }
                else
                {
                    s.Add(var, new UriNode(null, graphUri));
                }
                context.OutputMultiset.Add(s);
            }

            return context.OutputMultiset;
        }
 /// <summary>
 ///   Gets the numeric 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>
 public override object NumericValue(SparqlEvaluationContext context, int bindingID)
 {
     INode temp = _expr.Value(context, bindingID);
     if (temp != null)
     {
         if (temp.NodeType == NodeType.Literal)
         {
             ILiteralNode lit = (ILiteralNode) temp;
             if (lit.DataType != null)
             {
                 if (lit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeDateTime) ||
                     lit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeDate))
                 {
                     DateTimeOffset dt;
                     if (DateTimeOffset.TryParse(lit.Value, out dt))
                     {
                         return NumericValueInternal(dt);
                     }
                     throw new RdfQueryException(
                         "Unable to evaluate an XPath Date Time function as the value of the Date Time typed literal couldn't be parsed as a Date Time");
                 }
                 throw new RdfQueryException(
                     "Unable to evaluate an XPath Date Time function on a typed literal which is not a Date Time");
             }
             throw new RdfQueryException(
                 "Unable to evaluate an XPath Date Time function on an untyped literal argument");
         }
         throw new RdfQueryException(
             "Unable to evaluate an XPath Date Time function on a non-literal argument");
     }
     throw new RdfQueryException("Unable to evaluate an XPath Date Time function on a null argument");
 }
        /// <summary>
        /// Calculates the Numeric Value of this Expression as evaluated for a given Binding
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override object NumericValue(SparqlEvaluationContext context, int bindingID)
        {
            if (this._leftExpr is ISparqlNumericExpression && this._rightExpr is ISparqlNumericExpression)
            {
                ISparqlNumericExpression a, b;
                a = (ISparqlNumericExpression)this._leftExpr;
                b = (ISparqlNumericExpression)this._rightExpr;

                SparqlNumericType type = (SparqlNumericType)Math.Max((int)a.NumericType(context, bindingID), (int)b.NumericType(context, bindingID));

                switch (type)
                {
                    case SparqlNumericType.Integer:
                        return a.IntegerValue(context, bindingID) + b.IntegerValue(context, bindingID);
                    case SparqlNumericType.Decimal:
                        return a.DecimalValue(context, bindingID) + b.DecimalValue(context, bindingID);
                    case SparqlNumericType.Float:
                        return a.FloatValue(context, bindingID) + b.FloatValue(context, bindingID);
                    case SparqlNumericType.Double:
                        return a.DoubleValue(context, bindingID) + b.DoubleValue(context, bindingID);
                    default:
                        throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined");
                }
            }
            else
            {
                throw new RdfQueryException("Cannot evalute an Arithmetic Expression where the two sub-expressions are not Numeric Expressions");
            }
        }
Example #5
0
        /// <summary>
        /// Gets the Timezone of the Argument Expression as evaluated for the given Binding in the given Context
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            IValuedNode temp = this._expr.Evaluate(context, bindingID);
            if (temp != null)
            {
                DateTimeOffset dt = temp.AsDateTime();
                //Regex based check to see if the value has a Timezone component
                //If not then the result is a null
                if (!Regex.IsMatch(temp.AsString(), "(Z|[+-]\\d{2}:\\d{2})$")) return new StringNode(null, string.Empty);

                //Now we have a DateTime we can try and return the Timezone
                if (dt.Offset.Equals(TimeSpan.Zero))
                {
                    //If Zero it was specified as Z (which means UTC so zero offset)
                    return new StringNode(null, "Z");
                }
                else
                {
                    //If the Offset is outside the range -14 to 14 this is considered invalid
                    if (dt.Offset.Hours < -14 || dt.Offset.Hours > 14) return null;

                    //Otherwise it has an offset which is a given number of hours (and minutes)
                    return new StringNode(null, dt.Offset.Hours.ToString("00") + ":" + dt.Offset.Minutes.ToString("00"));
                }
            }
            else
            {
                throw new RdfQueryException("Unable to evaluate a Date Time function on a null argument");
            }
        }
 /// <summary>
 /// Computes the Effective Boolean Value of this Expression as evaluated for a given Binding
 /// </summary>
 /// <param name="context">Evaluation Context</param>
 /// <param name="bindingID">Binding ID</param>
 /// <returns></returns>
 public override bool EffectiveBooleanValue(SparqlEvaluationContext context, int bindingID)
 {
     //Lazy Evaluation for efficiency
     try
     {
         bool leftResult = this._leftExpr.EffectiveBooleanValue(context, bindingID);
         if (leftResult)
         {
             //If the LHS is true it doesn't matter about any subsequenct results
             return true;
         }
         else
         {
             //If the LHS is false then we have to evaluate the RHS
             return this._rightExpr.EffectiveBooleanValue(context, bindingID);
         }
     }
     catch
     {
         //If there's an Error on the LHS we return true only if the RHS evaluates to true
         //Otherwise we throw the Error
         bool rightResult = this._rightExpr.EffectiveBooleanValue(context, bindingID);
         if (rightResult)
         {
             return true;
         }
         else
         {
             throw;
         }
     }
 }
Example #7
0
        /// <summary>
        /// Returns the value of the Expression as evaluated for a given Binding as a Literal Node
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            INode result = this._expr.Evaluate(context, bindingID);
            if (result == null)
            {
                throw new RdfQueryException("Cannot return the Data Type URI of a NULL");
            }
            else
            {
                switch (result.NodeType)
                {
                    case NodeType.Literal:
                        ILiteralNode lit = (ILiteralNode)result;
                        if (lit.DataType == null)
                        {
                            if (!lit.Language.Equals(string.Empty))
                            {
                                return new UriNode(null, UriFactory.Create(RdfSpecsHelper.RdfLangString));
                            }
                            else
                            {
                                return new UriNode(null, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString));
                            }
                        }
                        else
                        {
                            return new UriNode(null, lit.DataType);
                        }

                    default:
                        throw new RdfQueryException("Cannot return the Data Type URI of Nodes which are not Literal Nodes");
                }
            }
        }
Example #8
0
        /// <summary>
        /// Calculates the Numeric Value of this Expression as evaluated for a given Binding
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            IValuedNode a = this._leftExpr.Evaluate(context, bindingID);
            IValuedNode b = this._rightExpr.Evaluate(context, bindingID);
            if (a == null || b == null) throw new RdfQueryException("Cannot apply division when one/both arguments are null");

            SparqlNumericType type = (SparqlNumericType)Math.Max((int)a.NumericType, (int)b.NumericType);

            try
            {
                switch (type)
                {
                    case SparqlNumericType.Integer:
                    case SparqlNumericType.Decimal:
                        //For Division Integers are treated as decimals
                        decimal d = a.AsDecimal() / b.AsDecimal();
                        if (Decimal.Floor(d).Equals(d) && d >= Int64.MinValue && d <= Int64.MaxValue)
                        {
                            return new LongNode(null, Convert.ToInt64(d));
                        }
                        return new DecimalNode(null, d);
                    case SparqlNumericType.Float:
                        return new FloatNode(null, a.AsFloat() / b.AsFloat());
                    case SparqlNumericType.Double:
                        return new DoubleNode(null, a.AsDouble() / b.AsDouble());
                    default:
                        throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined");
                }
            }
            catch (DivideByZeroException)
            {
                throw new RdfQueryException("Cannot evaluate a Division Expression where the divisor is Zero");
            }
        }
 /// <summary>
 /// Creates a new Path Evaluation Context
 /// </summary>
 /// <param name="context">SPARQL Evaluation Context</param>
 /// <param name="end">Start point of the Path</param>
 /// <param name="start">End point of the Path</param>
 public PathEvaluationContext(SparqlEvaluationContext context, PatternItem start, PatternItem end)
 {
     this._context = context;
     this._start = start;
     this._end = end;
     if (this._start.VariableName == null && this._end.VariableName == null) this._earlyAbort = true;
 }
Example #10
0
        /// <summary>
        /// Gets the Numeric Value of the function as evaluated in the given Context for the given Binding ID
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            IValuedNode a = this._expr.Evaluate(context, bindingID);
            if (a == null) throw new RdfQueryException("Cannot calculate an arithmetic expression on a null");

            switch (a.NumericType)
            {
                case SparqlNumericType.Integer:
                    return new LongNode(null, Math.Abs(a.AsInteger()));

                case SparqlNumericType.Decimal:
                    return new DecimalNode(null, Math.Abs(a.AsDecimal()));

                case SparqlNumericType.Float:
                    try
                    {
                        return new FloatNode(null, Convert.ToSingle(Math.Abs(a.AsDouble())));
                    }
                    catch (RdfQueryException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        throw new RdfQueryException("Unable to cast absolute value of float to a float", ex);
                    }

                case SparqlNumericType.Double:
                    return new DoubleNode(null, Math.Abs(a.AsDouble()));

                default:
                    throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined");
            }
        }
        /// <summary>
        /// Gets the Numeric Value of the function as evaluated in the given Context for the given Binding ID
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override object NumericValue(SparqlEvaluationContext context, int bindingID)
        {
            if (this._expr is ISparqlNumericExpression)
            {
                ISparqlNumericExpression a = (ISparqlNumericExpression)this._expr;

                switch (a.NumericType(context, bindingID))
                {
                    case SparqlNumericType.Integer:
                        return Math.Abs(a.IntegerValue(context, bindingID));

                    case SparqlNumericType.Decimal:
                        return Math.Abs(a.DecimalValue(context, bindingID));

                    case SparqlNumericType.Float:
                        return (float)Math.Abs(a.DoubleValue(context, bindingID));

                    case SparqlNumericType.Double:
                        return Math.Abs(a.DoubleValue(context, bindingID));
                        
                    default:
                        throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined");
                }
            }
            else
            {
                throw new RdfQueryException("Cannot evalute an Arithmetic Expression where the sub-expression is not a Numeric Expressions");
            }
        }
Example #12
0
        /// <summary>
        /// Generates the Description for each of the Nodes to be described
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="context">SPARQL Evaluation Context</param>
        /// <param name="nodes">Nodes to be described</param>
        protected override void DescribeInternal(IRdfHandler handler, SparqlEvaluationContext context, IEnumerable<INode> nodes)
        {
            //Rewrite Blank Node IDs for DESCRIBE Results
            Dictionary<String, INode> bnodeMapping = new Dictionary<string, INode>();

            //Get Triples for this Subject
            Queue<INode> bnodes = new Queue<INode>();
            HashSet<INode> expandedBNodes = new HashSet<INode>();
            INode rdfsLabel = handler.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "label"));
            foreach (INode n in nodes)
            {
                //Get Triples where the Node is the Subject
                foreach (Triple t in context.Data.GetTriplesWithSubject(n))
                {
                    if (t.Object.NodeType == NodeType.Blank)
                    {
                        if (!expandedBNodes.Contains(t.Object)) bnodes.Enqueue(t.Object);
                    }
                    if (!handler.HandleTriple((this.RewriteDescribeBNodes(t, bnodeMapping, handler)))) ParserHelper.Stop();
                }

                //Compute the Blank Node Closure for this Subject
                while (bnodes.Count > 0)
                {
                    INode bsubj = bnodes.Dequeue();
                    if (expandedBNodes.Contains(bsubj)) continue;
                    expandedBNodes.Add(bsubj);

                    foreach (Triple t2 in context.Data.GetTriplesWithSubjectPredicate(bsubj, rdfsLabel))
                    {
                        if (!handler.HandleTriple((this.RewriteDescribeBNodes(t2, bnodeMapping, handler)))) ParserHelper.Stop();
                    }
                }
            }
        }
Example #13
0
        /// <summary>
        /// Calculates the Numeric Value of this Expression as evaluated for a given Binding
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            IValuedNode a = this._expr.Evaluate(context, bindingID);
            if (a == null) throw new RdfQueryException("Cannot apply unary minus to a null");

            switch (a.NumericType)
            {
                case SparqlNumericType.Integer:
                    return new LongNode(null, -1 * a.AsInteger());

                case SparqlNumericType.Decimal:
                    decimal decvalue = a.AsDecimal();
                    if (decvalue == Decimal.Zero)
                    {
                        return new DecimalNode(null, Decimal.Zero);
                    }
                    else
                    {
                        return new DecimalNode(null, -1 * decvalue);
                    }
                case SparqlNumericType.Float:
                    float fltvalue = a.AsFloat();
                    if (Single.IsNaN(fltvalue))
                    {
                        return new FloatNode(null, Single.NaN);
                    }
                    else if (Single.IsPositiveInfinity(fltvalue))
                    {
                        return new FloatNode(null, Single.NegativeInfinity);
                    }
                    else if (Single.IsNegativeInfinity(fltvalue))
                    {
                        return new FloatNode(null, Single.PositiveInfinity);
                    }
                    else
                    {
                        return new FloatNode(null, -1.0f * fltvalue);
                    }
                case SparqlNumericType.Double:
                    double dblvalue = a.AsDouble();
                    if (Double.IsNaN(dblvalue))
                    {
                        return new DoubleNode(null, Double.NaN);
                    }
                    else if (Double.IsPositiveInfinity(dblvalue))
                    {
                        return new DoubleNode(null, Double.NegativeInfinity);
                    }
                    else if (Double.IsNegativeInfinity(dblvalue))
                    {
                        return new DoubleNode(null, Double.PositiveInfinity);
                    }
                    else
                    {
                        return new DoubleNode(null, -1.0 * dblvalue);
                    }
                default:
                    throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined");
            }
        }
Example #14
0
        /// <summary>
        /// Evaluates a Filter in the given Evaluation Context
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        public override void Evaluate(SparqlEvaluationContext context)
        {
            if (context.InputMultiset is NullMultiset)
            {
                //If we get a NullMultiset then the FILTER has no effect since there are already no results
            }
            else if (context.InputMultiset is IdentityMultiset)
            {
                if (!this._filter.Variables.Any())
                {
                    //If we get an IdentityMultiset then the FILTER only has an effect if there are no
                    //variables - otherwise it is not in scope and is ignored

                    try
                    {
                        if (!this._filter.Expression.EffectiveBooleanValue(context, 0))
                        {
                            context.OutputMultiset = new NullMultiset();
                            return;
                        }
                    }
                    catch
                    {
                        context.OutputMultiset = new NullMultiset();
                        return;
                    }
                }
            }
            else
            {
                this._filter.Evaluate(context);
            }
            context.OutputMultiset = new IdentityMultiset();
        }
        /// <summary>
        /// Gets the Numeric Value of the Function as evaluated in the given Context for the given Binding ID
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override object NumericValue(SparqlEvaluationContext context, int bindingID)
        {
            if (this._expr is ISparqlNumericExpression)
            {
                ISparqlNumericExpression a = (ISparqlNumericExpression)this._expr;

                SparqlNumericType type = a.NumericType(context, bindingID);
                switch (type)
                {
                    case SparqlNumericType.Integer:
                        return this.IntegerValueInternal(a.IntegerValue(context, bindingID));
                    case SparqlNumericType.Decimal:
                        return this.DecimalValueInternal(a.DecimalValue(context, bindingID));
                    case SparqlNumericType.Double:
                        return this.DoubleValueInternal(a.DoubleValue(context, bindingID));
                    case SparqlNumericType.NaN:
                    default:
                        throw new RdfQueryException("Unable to evaluate a Leviathan Numeric Expression since the inner expression did not evaluate to a Numeric Value");
                }
            }
            else
            {
                throw new RdfQueryException("Unable to evaluate a Leviathan Numeric Expression since the inner expression is not a Numeric Expression");
            }
        }
Example #16
0
        /// <summary>
        /// Evaluates an ExistsJoin
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <returns></returns>
        public BaseMultiset Evaluate(SparqlEvaluationContext context)
        {
            BaseMultiset initialInput = context.InputMultiset;
            BaseMultiset lhsResult = context.Evaluate(this._lhs);//this._lhs.Evaluate(context);
            context.CheckTimeout();

            if (lhsResult is NullMultiset)
            {
                context.OutputMultiset = lhsResult;
            }
            else if (lhsResult.IsEmpty)
            {
                context.OutputMultiset = new NullMultiset();
            }
            else
            {
                //Only execute the RHS if the LHS had results
                context.InputMultiset = lhsResult;
                BaseMultiset rhsResult = context.Evaluate(this._rhs);//this._rhs.Evaluate(context);
                context.CheckTimeout();

                context.OutputMultiset = lhsResult.ExistsJoin(rhsResult, this._mustExist);
                context.CheckTimeout();
            }

            context.InputMultiset = context.OutputMultiset;
            return context.OutputMultiset;
        }
Example #17
0
 /// <summary>
 /// Gets the Value of the function as evaluated in the given Context for the given Binding ID
 /// </summary>
 /// <param name="context">Context</param>
 /// <param name="bindingID">Binding ID</param>
 /// <returns></returns>
 public INode Value(SparqlEvaluationContext context, int bindingID)
 {
     INode temp = this._expr.Value(context, bindingID);
     if (temp != null)
     {
         if (temp.NodeType == NodeType.Literal)
         {
             ILiteralNode lit = (ILiteralNode)temp;
             if (lit.DataType != null)
             {
                 if (lit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString))
                 {
                     return this.ValueInternal(lit);
                 }
                 else
                 {
                     throw new RdfQueryException("Unable to evalaute an XPath String function on a non-string typed Literal");
                 }
             }
             else
             {
                 return this.ValueInternal(lit);
             }
         }
         else
         {
             throw new RdfQueryException("Unable to evaluate an XPath String function on a non-Literal input");
         }
     }
     else
     {
         throw new RdfQueryException("Unable to evaluate an XPath String function on a null input");
     }
 }
        /// <summary>
        /// Returns the Graph which is the Result of the Describe Query by computing the Concise Bounded Description for all Results
        /// </summary>
        /// <param name="context">SPARQL Evaluation Context</param>
        /// <returns></returns>
        public override IGraph Describe(SparqlEvaluationContext context)
        {
            //Get a new empty Graph and import the Base Uri and Namespace Map of the Query
            Graph g = new Graph();
            g.BaseUri = context.Query.BaseUri;
            g.NamespaceMap.Import(context.Query.NamespaceMap);

            //Build a list of INodes to describe
            List<INode> nodes = new List<INode>();
            foreach (IToken t in context.Query.DescribeVariables)
            {
                switch (t.TokenType)
                {
                    case Token.QNAME:
                    case Token.URI:
                        //Resolve Uri/QName
                        nodes.Add(new UriNode(g, new Uri(Tools.ResolveUriOrQName(t, g.NamespaceMap, g.BaseUri))));
                        break;

                    case Token.VARIABLE:
                        //Get Variable Values
                        String var = t.Value.Substring(1);
                        if (context.OutputMultiset.ContainsVariable(var))
                        {
                            foreach (Set s in context.OutputMultiset.Sets)
                            {
                                INode temp = s[var];
                                if (temp != null) nodes.Add(temp);
                            }
                        }
                        break;

                    default:
                        throw new RdfQueryException("Unexpected Token '" + t.GetType().ToString() + "' in DESCRIBE Variables list");
                }
            }

            //Rewrite Blank Node IDs for DESCRIBE Results
            Dictionary<String, INode> bnodeMapping = new Dictionary<string, INode>();

            //Get Triples for this Subject
            foreach (INode n in nodes)
            {
                //Get Triples where the Node is the Subject
                foreach (Triple t in context.Data.GetTriplesWithSubject(n))
                {
                    g.Assert(this.RewriteDescribeBNodes(t, bnodeMapping, g));
                }
                //Get Triples where the Node is the Object
                foreach (Triple t in context.Data.GetTriplesWithObject(n))
                {
                    g.Assert(this.RewriteDescribeBNodes(t, bnodeMapping, g));
                }
            }

            //Return the Graph
            g.BaseUri = null;
            return g;
        }
        /// <summary>
        /// Evaluates the expression
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            IValuedNode temp = this._expr.Evaluate(context, bindingID);
            if (temp == null) throw new RdfQueryException("Cannot apply a trigonometric function to a null");

            if (temp.NumericType == SparqlNumericType.NaN) throw new RdfQueryException("Cannot apply a trigonometric function to a non-numeric argument");

            return new DoubleNode(null, this._func(temp.AsDouble()));
        }
Example #20
0
        /// <summary>
        /// Evaluates the subquery in the given context
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <returns></returns>
        public BaseMultiset Evaluate(SparqlEvaluationContext context)
        {
            //Use the same algebra optimisers as the parent query (if any)
            if (context.Query != null)
            {
                this._subquery.AlgebraOptimisers = context.Query.AlgebraOptimisers;
            }

            if (context.InputMultiset is NullMultiset)
            {
                context.OutputMultiset = context.InputMultiset;
            }
            else if (context.InputMultiset.IsEmpty)
            {
                context.OutputMultiset = new NullMultiset();
            }
            else
            {
                SparqlEvaluationContext subcontext = new SparqlEvaluationContext(this._subquery, context.Data, context.Processor);
                subcontext.InputMultiset = context.InputMultiset;

                //Add any Named Graphs to the subquery
                if (context.Query != null)
                {
                    foreach (Uri u in context.Query.NamedGraphs)
                    {
                        this._subquery.AddNamedGraph(u);
                    }
                }

                ISparqlAlgebra query = this._subquery.ToAlgebra();
                try
                {
                    //Evaluate the Subquery
                    context.OutputMultiset = subcontext.Evaluate(query);

                    //If the Subquery contains a GROUP BY it may return a Group Multiset in which case we must flatten this to a Multiset
                    if (context.OutputMultiset is GroupMultiset)
                    {
                        context.OutputMultiset = new Multiset((GroupMultiset)context.OutputMultiset);
                    }

                    //Strip out any Named Graphs from the subquery
                    if (this._subquery.NamedGraphs.Any())
                    {
                        this._subquery.ClearNamedGraphs();
                    }
                }
                catch (RdfQueryException queryEx)
                {
                    throw new RdfQueryException("Query failed due to a failure in Subquery Execution:\n" + queryEx.Message, queryEx);
                }
            }

            return context.OutputMultiset;
        }
        /// <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>
        public INode Value(SparqlEvaluationContext context, int bindingID)
        {
            ILiteralNode input = CheckArgument(_expr, context, bindingID);
            ILiteralNode start = CheckArgument(_start, context, bindingID, XPathFunctionFactory.AcceptNumericArguments);

            if (_end != null)
            {
                ILiteralNode end = CheckArgument(_end, context, bindingID, XPathFunctionFactory.AcceptNumericArguments);

                if (input.Value.Equals(String.Empty))
                    return new LiteralNode(null, String.Empty, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));

                try
                {
                    int s = Convert.ToInt32(start.Value);
                    int e = Convert.ToInt32(end.Value);

                    if (s < 0) s = 0;
                    if (e < s)
                    {
                        //If no/negative characters are being selected the empty string is returned
                        return new LiteralNode(null, String.Empty, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
                    }
                    if (s > input.Value.Length)
                    {
                        //If the start is after the end of the string the empty string is returned
                        return new LiteralNode(null, String.Empty, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
                    }
                    return e > input.Value.Length
                               ? new LiteralNode(null, input.Value.Substring(s),
                                                 new Uri(XmlSpecsHelper.XmlSchemaDataTypeString))
                               : new LiteralNode(null, input.Value.Substring(s, e - s),
                                                 new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
                }
                catch
                {
                    throw new RdfQueryException("Unable to convert the Start/End argument to an Integer");
                }
            }
            if (input.Value.Equals(String.Empty))
                return new LiteralNode(null, String.Empty, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));

            try
            {
                int s = Convert.ToInt32(start.Value);
                if (s < 0) s = 0;

                return new LiteralNode(null, input.Value.Substring(s),
                                       new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
            }
            catch
            {
                throw new RdfQueryException("Unable to convert the Start argument to an Integer");
            }
        }
 /// <summary>
 /// Checks whether the pattern accepts the given Node
 /// </summary>
 /// <param name="context">SPARQL Evaluation Context</param>
 /// <param name="obj">Node to test</param>
 /// <returns></returns>
 protected internal override bool Accepts(SparqlEvaluationContext context, INode obj)
 {
     if (obj.NodeType == NodeType.Blank)
     {
         return ((IBlankNode)obj).InternalID.Equals(this._id);
     }
     else
     {
         return false;
     }
 }
Example #23
0
        /// <summary>
        /// Casts the results of the inner expression to a Literal Node typed xsd:string
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            IValuedNode n = this._expr.Evaluate(context, bindingID);

            if (n == null)
            {
                throw new RdfQueryException("Cannot cast a Null to a xsd:string");
            }

            return new StringNode(null, n.AsString(), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString));
        }
 /// <summary>
 /// Checks whether the given Node matches the Node this pattern was instantiated with
 /// </summary>
 /// <param name="context">Evaluation Context</param>
 /// <param name="obj">Node to test</param>
 /// <returns></returns>
 protected internal override bool Accepts(SparqlEvaluationContext context, INode obj)
 {
     //if (context.RigorousEvaluation)
     //{
         return this._node.Equals(obj);
     //}
     //else
     //{
     //    return true;
     //}
 }
Example #25
0
 /// <summary>
 /// Computes the Effective Boolean Value of this Expression as evaluated for a given Binding
 /// </summary>
 /// <param name="context">Evaluation Context</param>
 /// <param name="bindingID">Binding ID</param>
 /// <returns></returns>
 public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
 {
     INode result = this._expr.Evaluate(context, bindingID);
     if (result == null)
     {
         return new BooleanNode(null, false);
     }
     else
     {
         return new BooleanNode(null, result.NodeType == NodeType.Uri);
     }
 }
 /// <summary>
 /// Gets the numeric 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>
 public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
 {
     IValuedNode temp = this._expr.Evaluate(context, bindingID);
     if (temp != null)
     {
         return this.ValueInternal(temp.AsDateTime());
     }
     else
     {
         throw new RdfQueryException("Unable to evaluate an XPath Date Time function on a null argument");
     }
 }
        /// <summary>
        /// Evaluates the Union
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public BaseMultiset Evaluate(SparqlEvaluationContext context)
        {
            //Create a copy of the evaluation context for the RHS
            SparqlEvaluationContext context2 = new SparqlEvaluationContext(context.Query, context.Data, context.Processor);
            if (!(context.InputMultiset is IdentityMultiset))
            {
                context2.InputMultiset = new Multiset();
                foreach (ISet s in context.InputMultiset.Sets)
                {
                    context2.InputMultiset.Add(s.Copy());
                }
            }

            IGraph activeGraph = context.Data.ActiveGraph;
            IGraph defaultGraph = context.Data.DefaultGraph;

            ParallelEvaluateDelegate d = new ParallelEvaluateDelegate(this.ParallelEvaluate);
            IAsyncResult lhs = d.BeginInvoke(this._lhs, context, activeGraph, defaultGraph, null, null);
            IAsyncResult rhs = d.BeginInvoke(this._rhs, context2, activeGraph, defaultGraph, null, null);

            WaitHandle.WaitAll(new WaitHandle[] { lhs.AsyncWaitHandle, rhs.AsyncWaitHandle });

            bool rhsOk = false;
            try 
            {
                BaseMultiset lhsResult = d.EndInvoke(lhs);
                rhsOk = true;
                BaseMultiset rhsResult = d.EndInvoke(rhs);
                context.CheckTimeout();

                context.OutputMultiset = lhsResult.Union(rhsResult);
                context.CheckTimeout();

                context.InputMultiset = context.OutputMultiset;
                return context.OutputMultiset;
            }
            catch 
            {
                if (!rhsOk)
                {
                    //Clean up the RHS evaluation call if the LHS has errored
                    try
                    {
                        d.EndInvoke(rhs);
                    }
                    catch
                    {
                        //Ignore this error as we're already going to throw the other error
                    }
                }
                throw;
            }
        }
Example #28
0
        public BaseMultiset Evaluate(SparqlEvaluationContext context)
        {
            //First evaluate the inner algebra
            BaseMultiset results = context.Evaluate(this._inner);
            context.OutputMultiset = new Multiset();

            if (results is NullMultiset)
            {
                context.OutputMultiset = results;
            }
            else if (results is IdentityMultiset)
            {
                context.OutputMultiset.AddVariable(this._var);
                Set s = new Set();
                try
                {
                    INode temp = this._expr.Value(context, 0);
                    s.Add(this._var, temp);
                }
                catch
                {
                    //No assignment if there's an error
                    s.Add(this._var, null);
                }
                context.OutputMultiset.Add(s);
            }
            else
            {
                if (results.ContainsVariable(this._var))
                {
                    throw new RdfQueryException("Cannot use a BIND assigment to BIND to a variable that has previously been used in the Query");
                }

                context.OutputMultiset.AddVariable(this._var);
                foreach (int id in results.SetIDs.ToList())
                {
                    Set s = new Set(results[id]);
                    try
                    {
                        //Make a new assignment
                        INode temp = this._expr.Value(context, id);
                        s.Add(this._var, temp);
                    }
                    catch
                    {
                        //No assignment if there's an error but the solution is preserved
                    }
                    context.OutputMultiset.Add(s);
                }
            }

            return context.OutputMultiset;
        }
 public override object NumericValue(SparqlEvaluationContext context, int bindingID)
 {
     INode value = this._expr.Value(context, bindingID);
     if (value != null)
     {
         if (value.NodeType == NodeType.Literal)
         {
             ILiteralNode lit = (ILiteralNode)value;
             if (!lit.Language.Equals(String.Empty))
             {
                 //If there's a Language Tag implied type is string so no numeric value
                 throw new RdfQueryException("Cannot calculate the Numeric Value of literal with a language specifier");
             }
             else if (lit.DataType == null)
             {
                 throw new RdfQueryException("Cannot calculate the Numeric Value of an untyped Literal");
             }
             else
             {
                 try
                 {
                     switch (SparqlSpecsHelper.GetNumericTypeFromDataTypeUri(lit.DataType))
                     {
                         case SparqlNumericType.Decimal:
                             return Decimal.Parse(lit.Value);
                         case SparqlNumericType.Double:
                             return Double.Parse(lit.Value);
                         case SparqlNumericType.Float:
                             return Single.Parse(lit.Value);
                         case SparqlNumericType.Integer:
                             return Int64.Parse(lit.Value);
                         case SparqlNumericType.NaN:
                         default:
                             throw new RdfQueryException("Cannot calculate the Numeric Value of a literal since its Data Type URI does not correspond to a Data Type URI recognised as a Numeric Type in the SPARQL Specification");
                     }
                 }
                 catch (FormatException fEx)
                 {
                     throw new RdfQueryException("Cannot calculate the Numeric Value of a Literal since the Value contained is not a valid value in it's given Data Type", fEx);
                 }
             }
         }
         else
         {
             throw new RdfQueryException("Cannot evaluate a numeric expression when the inner expression evaluates to a non-literal node");
         }
     }
     else
     {
         throw new RdfQueryException("Cannot evaluate a numeric expression when the inner expression evaluates to null");
     }
 }
Example #30
0
        /// <summary>
        /// Returns the value of the Expression as evaluated for a given Binding as a Literal Node
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            INode s = this._leftExpr.Evaluate(context, bindingID);
            INode dt = this._rightExpr.Evaluate(context, bindingID);

            if (s != null)
            {
                if (dt != null)
                {
                    Uri dtUri;
                    if (dt.NodeType == NodeType.Uri)
                    {
                        dtUri = ((IUriNode)dt).Uri;
                    }
                    else
                    {
                        throw new RdfQueryException("Cannot create a datatyped literal when the datatype is a non-URI Node");
                    }
                    if (s.NodeType == NodeType.Literal)
                    {
                        ILiteralNode lit = (ILiteralNode)s;
                        if (lit.DataType == null)
                        {
                            if (lit.Language.Equals(string.Empty))
                            {
                                return new StringNode(null, lit.Value, dtUri);
                            }
                            else
                            {
                                throw new RdfQueryException("Cannot create a datatyped literal from a language specified literal");
                            }
                        }
                        else
                        {
                            throw new RdfQueryException("Cannot create a datatyped literal from a typed literal");
                        }
                    }
                    else
                    {
                        throw new RdfQueryException("Cannot create a datatyped literal from a non-literal Node");
                    }
                }
                else
                {
                    throw new RdfQueryException("Cannot create a datatyped literal from a null string");
                }
            }
            else
            {
                throw new RdfQueryException("Cannot create a datatyped literal from a null string");
            }
        }