示例#1
0
 private bool nextIsMatchingVarPattern(ITriplePattern main, List <IElement> elements, int i)
 {
     if (main.getObject() is IVariable &&
         i < elements.Count - 2 &&
         elements[i + 1] is ITriplePattern &&
         elements[i + 2] is ITriplePattern)
     {
         IVariable mainVar = (IVariable)main.getObject();
         if (mainVar.isBlankNodeVar())
         {
             ITriplePattern nextPattern = (ITriplePattern)elements[i + 1];
             ITriplePattern lastPattern = (ITriplePattern)elements[i + 2];
             IResource      nextSubject = nextPattern.getSubject();
             IResource      lastSubject = lastPattern.getSubject();
             if (nextSubject is IVariable &&
                 lastSubject is IVariable &&
                 RDFUtil.sameTerm(RDF.PropertyFirst, nextPattern.getPredicate()) &&
                 RDFUtil.sameTerm(RDF.PropertyRest, lastPattern.getPredicate()))
             {
                 IVariable nextVar = (IVariable)nextSubject;
                 if (mainVar.getName().Equals(nextVar.getName()))
                 {
                     IVariable lastVar = (IVariable)lastSubject;
                     return(mainVar.getName().Equals(lastVar.getName()));
                 }
             }
         }
     }
     return(false);
 }
 override public void visit(IVariable variable)
 {
     if (RDFUtil.sameTerm(_var, variable))
     {
         _checker.setResult();
     }
 }
示例#3
0
        public List <Dictionary <String, IResource> > getBindings()
        {
            List <String> varNames = getVarNames();
            List <Dictionary <String, IResource> > bindings = new List <Dictionary <String, IResource> >();
            List <IResource> outerList = getResource(SP.PropertyBindings).AsList();

            if (outerList != null)
            {
                foreach (IResource innerList in outerList)
                {
                    Dictionary <String, IResource> binding = new Dictionary <String, IResource>();
                    bindings.Add(binding);
                    IEnumerator <String>    vars   = varNames.GetEnumerator();
                    IEnumerator <IResource> values = innerList.AsList().GetEnumerator();
                    while (vars.MoveNext())
                    {
                        String    varName = vars.Current;
                        IResource value   = values.Current;
                        if (!RDFUtil.sameTerm(SP.ClassPropertyUndef, value))
                        {
                            binding.Add(varName, value);
                        }
                    }
                }
            }
            return(bindings);
        }
示例#4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="spinGraph"></param>
        /// <returns></returns>
        internal IGraph Initialise(IGraph spinGraph)
        {
            if (_spinConfiguration.GraphUris.Contains(spinGraph.BaseUri))
            {
                _spinConfiguration.RemoveGraph(spinGraph.BaseUri);
            }
            String ontQuery = "CONSTRUCT { ?graphUri a <" + SPIN.ClassLibraryOntology + ">} WHERE { {?s (<" + SPIN.PropertyImports + ">|<" + OWL.PropertyImports + ">) ?graphUri} UNION {?graphUri a <" + SPIN.ClassLibraryOntology + ">} }";
            IGraph imports  = (Graph)spinGraph.ExecuteQuery(ontQuery);

            // Explore for subsequent imports
            foreach (Triple t in imports.GetTriplesWithPredicateObject(RDF.PropertyType, SPIN.ClassLibraryOntology))
            {
                Uri importUri = ((IUriNode)t.Subject).Uri;
                if (!_spinConfiguration.GraphUris.Contains(importUri) && !RDFUtil.sameTerm(importUri, spinGraph.BaseUri))
                {
                    Initialise(importUri);
                }
            }
            _spinConfiguration.AddGraph(spinGraph);
            _reasoner.Initialise(spinGraph);

            IGraph inferenceGraph = ApplyInference(spinGraph);

            _spinConfiguration.AddGraph(inferenceGraph);
            _reasoner.Initialise(inferenceGraph);

            return(inferenceGraph);
        }
示例#5
0
 /**
  *
  * @param constaint is a statement whose subject is a class, and whose predicate is SPIN.constraint
  * @param results
  */
 private void addArgumentFromConstraint(Triple constraint, List <IArgument> results)
 {
     if (constraint.Object is IBlankNode)
     {
         // Optimized case to avoid walking up class hierarchy
         IEnumerator <Triple> types = Resource.Get(constraint.Object, getModel()).listProperties(RDF.PropertyType).GetEnumerator();
         while (types.MoveNext())
         {
             Triple typeS = types.Current;
             if (typeS.Object is IUriNode)
             {
                 if (RDFUtil.sameTerm(SPL.ClassArgument, typeS.Object))
                 {
                     results.Add(SPINFactory.asArgument(Resource.Get(constraint.Object, getModel())));
                 }
                 else if (!RDFUtil.sameTerm(SPL.ClassAttribute, typeS.Object))
                 {
                     if (Resource.Get(typeS.Object, getModel()).hasProperty(RDFS.PropertySubClassOf, SPL.ClassArgument))
                     {
                         results.Add(SPINFactory.asArgument(Resource.Get(constraint.Object, getModel())));
                     }
                 }
             }
         }
     }
     else if (constraint.Object is IUriNode && Resource.Get(constraint.Object, getModel()).hasProperty(RDFS.PropertySubClassOf, SPL.ClassArgument))
     {
         results.Add(SPINFactory.asArgument(Resource.Get(constraint.Object, getModel())));
     }
 }
 override public void visit(ITriplePath triplePath)
 {
     if (RDFUtil.sameTerm(_var, triplePath.getObject()) ||
         RDFUtil.sameTerm(_var, triplePath.getSubject()))
     {
         _checker.setResult();
     }
 }
示例#7
0
        // Special treatment of nested rdf:Lists
        private int printTriplePattern(List <IElement> elements, int i, ISparqlPrinter p)
        {
            ITriplePattern main = (ITriplePattern)elements[i];

            // Print subject
            List <IResource> leftList = new List <IResource>();

            i = addListMembers(elements, i, leftList);
            if (leftList.Count == 0)
            {
                TupleImpl.print(getModel(), main.getSubject(), p);
            }
            else
            {
                printRDFList(p, leftList);
                main = (ITriplePattern)elements[i];
            }
            p.print(" ");

            // Print predicate
            if (RDFUtil.sameTerm(RDF.PropertyType, main.getPredicate()))
            {
                p.print("a");
            }
            else
            {
                TupleImpl.print(getModel(), main.getPredicate(), p);
            }
            p.print(" ");

            // Print object
            if (nextIsMatchingVarPattern(main, elements, i))
            {
                List <IResource> rightList = new List <IResource>();
                i = addListMembers(elements, i + 1, rightList);
                if (rightList.Count == 0)
                {
                    TupleImpl.print(getModel(), main.getObject(), p);
                    if (leftList.Count != 0)
                    {
                        i--;
                    }
                }
                else
                {
                    printRDFList(p, rightList);
                    i--;
                }
            }
            else
            {
                TupleImpl.print(getModel(), main.getObject(), p);
            }
            return(i);
        }
示例#8
0
 internal void SortClasses(List <Resource> classList)
 {
     classList.Sort(delegate(Resource x, Resource y)
     {
         if (RDFUtil.sameTerm(x, y))
         {
             return(0);
         }
         if (ContainsTriple(x, RDFS.PropertySubClassOf, y))
         {
             return(1);
         }
         return(-1);
     });
 }
示例#9
0
 internal void SortProperties(List <Resource> propertyList)
 {
     propertyList.Sort(delegate(Resource x, Resource y)
     {
         if (RDFUtil.sameTerm(x, y))
         {
             return(0);
         }
         if (ContainsTriple(x, RDFS.PropertySubPropertyOf, y))
         {
             return(1);
         }
         return(-1);
     });
 }
        public Dictionary <IResource, IResource> getArgumentsMap()
        {
            /*sealed*/
            Dictionary <IResource, IResource> values = new Dictionary <IResource, IResource>();
            IEnumerator <Triple> it = listProperties().GetEnumerator();

            while (it.MoveNext())
            {
                Triple s = it.Current;
                if (!RDFUtil.sameTerm(RDF.PropertyType, s.Predicate))
                {
                    values[Resource.Get(s.Predicate, getModel())] = Resource.Get(s.Object, getModel());
                }
            }
            return(values);
        }
示例#11
0
 /**
  * Checks if a given INode might represent a Function call, and if
  * yes returns the resource as Function.  The condition here is fairly
  * general: a function call must be a blank node with an rdf:type triple
  * where the type triple's object is a URI resource.  It is generally
  * assumed that this function is called after other options have been
  * exhausted.  For example, in order to test whether a resource is a
  * variable or a function call, the variable test must be done first
  * as it is more specific than these test conditions
  * @param resource  the INode to test
  * @return resource as a Function or null if resource cannot be cast
  */
 public static IFunctionCall asFunctionCall(IResource resource)
 {
     if (resource == null)
     {
         return(null);
     }
     if (resource is IBlankNode)
     {
         IResource t = resource.getResource(RDF.PropertyType);
         if (t != null && !RDFUtil.sameTerm(SP.ClassVariable, t))
         {
             return((IFunctionCall)resource.As(typeof(FunctionCallImpl)));
         }
     }
     return(null);
 }
示例#12
0
        private String getPrefix(Uri ns, ISparqlPrinter context)
        {
            String prefix = getSource().Graph.NamespaceMap.GetPrefix(ns);

            if (prefix == null && context.getUseExtraPrefixes())
            {
                INamespaceMapper extras = ExtraPrefixes.getExtraPrefixes();
                foreach (String extraPrefix in extras.Prefixes)
                {
                    Uri extraNs = extras.GetNamespaceUri(extraPrefix);
                    if (RDFUtil.sameTerm(ns, extraNs))
                    {
                        return(extraPrefix);
                    }
                }
            }
            return(prefix);
        }
示例#13
0
        /**
         * Gets an spl:Attribute defined for a given property on a given class.
         * The spl:Attribute must be a direct spin:constraint on the class.
         * @param cls  the class
         * @param property  the property
         * @return the Attribute or null if none is found
         */
        public static IAttribute getAttribute(IResource cls, INode property)
        {
            IEnumerator <Triple> it = cls.listProperties(SPIN.PropertyConstraint).GetEnumerator();

            while (it.MoveNext())
            {
                IResource obj = Resource.Get(it.Current.Object, cls.getModel());
                if (obj is INode && ((IResource)obj).hasProperty(RDF.PropertyType, SPL.ClassAttribute))
                {
                    IAttribute a = (IAttribute)obj.As(typeof(AttributeImpl));
                    if (RDFUtil.sameTerm(property, a.getPredicate()))
                    {
                        it.Dispose();
                        return(a);
                    }
                }
            }
            return(null);
        }
示例#14
0
        private int addListMembers(List <IElement> elements, int i, List <IResource> members)
        {
            bool first = true;

            while (i < elements.Count - 1 &&
                   elements[i] is ITriplePattern &&
                   elements[i + 1] is ITriplePattern)
            {
                ITriplePattern firstPattern  = (ITriplePattern)elements[i];
                ITriplePattern secondPattern = (ITriplePattern)elements[i + 1];
                if (RDFUtil.sameTerm(RDF.PropertyFirst, firstPattern.getPredicate()) && RDFUtil.sameTerm(RDF.PropertyRest, secondPattern.getPredicate()))
                {
                    IResource firstSubject  = firstPattern.getSubject();
                    IResource secondSubject = secondPattern.getSubject();
                    if (firstSubject is IVariable && secondSubject is IVariable)
                    {
                        IVariable firstVar  = (IVariable)firstSubject;
                        IVariable secondVar = (IVariable)secondSubject;
                        if (firstVar.isBlankNodeVar() && firstVar.getName().Equals(secondVar.getName()))
                        {
                            members.Add(firstPattern.getObject());
                            IResource secondObject = secondPattern.getObject();
                            i++;
                            if (RDFUtil.sameTerm(RDF.Nil, secondObject))
                            {
                                return(i + 1);
                            }
                        }
                    }
                }

                // We are not in a valid list
                if (first && members.Count == 0)
                {
                    break;
                }
                first = false;
                i++;
            }
            return(i);
        }
示例#15
0
 public static void print(SpinProcessor model, IResource node, ISparqlPrinter p, bool abbrevRDFType)
 {
     // TODO find the good tests ?????
     if (!node.isLiteral())
     {
         if (abbrevRDFType && RDFUtil.sameTerm(RDF.PropertyType, node))
         {
             p.print("a");
         }
         else
         {
             printVarOrResource(p, node);
         }
     }
     else
     {
         //TODO INamespaceMapper pm = p.getUsePrefixes() ? model.getGraph().getPrefixMapping() : SPINExpressions.emptyPrefixMapping;
         String str = node.getSource().ToString();// TODO is this correct ? // FmtUtils.stringForNode(node, null/*TODO pm*/);
         p.print(str);
     }
 }
        override public void Print(ISparqlPrinter p)
        {
            IResource        function = getFunction();
            List <IResource> args     = getArguments();

            String symbol = getSymbol(function);

            //TODO implement isLetter
            if (symbol != null && (/*TODO !symbol[0].isLetter() ||*/ isSetOperator(symbol)))
            {
                printOperator(p, symbol, args);
            }
            else if (symbol != null && (RDFUtil.sameTerm(SP.PropertyExists, function) || RDFUtil.sameTerm(SP.PropertyNotExists, function)))
            {
                printExistsOrNotExists(p, symbol);
            }
            else
            {
                printFunction(p, function, args);
            }
        }
示例#17
0
        /**
         * Checks if a given INode can be cast into an ElementList.
         * It must be either rdf:nil or an rdf:List where the first
         * list item is an element using <code>asElement()</code>.
         * @param resource  the resource to test
         * @return true if resource is an element list
         */
        public static bool isElementList(IResource resource)
        {
            if (resource.isUri() && RDFUtil.sameTerm(RDF.Nil, resource))
            {
                return(true);
            }
            else
            {
                return(resource.hasProperty(RDF.PropertyFirst));

                /*
                 * ITriple firstS = Model.getProperty(Model, resource, RDF.first);
                 * if (firstS != null && !(firstS.Object is ILiteralNode))
                 * {
                 *  INode first = firstS.Object;
                 *  return asElement(first) != null;
                 * }
                 * else
                 * {
                 *  return false;
                 * }
                 */
            }
        }
        private IResource[] getArgumentProperties(Dictionary <IResource, IResource> values)
        {
            IResource[]      ps     = new IResource[values.Count];
            List <IResource> others = new List <IResource>();

            foreach (IResource p in values.Keys)
            {
                if (p.Uri.ToString().StartsWith(SP_ARG) && !RDFUtil.sameTerm(p, SP.PropertyArg))
                {
                    int index = int.Parse(p.Uri.ToString().Substring(SP_ARG.Length));
                    ps[index - 1] = p;
                }
                else
                {
                    others.Add(p);
                }
            }
            if (others.Count > 0)
            {
                others.Sort(delegate(IResource arg0, IResource arg1)
                {
                    //TODO is that OK ?
                    return(RDFUtil.uriComparer.Compare(arg0.Uri, arg1.Uri));
                }
                            );
                IEnumerator <IResource> it = others.GetEnumerator();
                for (int i = 0; i < ps.Length; i++)
                {
                    if (ps[i] == null)
                    {
                        ps[i] = it.Current;
                    }
                }
            }
            return(ps);
        }
示例#19
0
 private ISparqlPath createPath(IResource path)
 {
     if (path.isUri())
     {
         return(new Property(path.getSource()));
     }
     else
     {
         IResource typeS = path.getResource(RDF.PropertyType);
         if (typeS != null && typeS.isUri())
         {
             INode type = typeS;
             if (RDFUtil.sameTerm(SP.ClassAltPath, type))
             {
                 ISparqlPath leftPath  = createPath(path, SP.PropertyPath1);
                 ISparqlPath rightPath = createPath(path, SP.PropertyPath2);
                 return(new AlternativePath(leftPath, rightPath));
             }
             else if (RDFUtil.sameTerm(SP.ClassModPath, type))
             {
                 ISparqlPath subPath = createPath(path, SP.PropertySubPath);
                 int?        min     = path.getInteger(SP.PropertyModMin);
                 int?        max     = path.getInteger(SP.PropertyModMax);
                 if (max == null || max < 0)
                 {
                     if (min == 1)
                     {
                         return(new OneOrMore(subPath));  // TODO: is this correct?
                     }
                     else if (min == null || min == -1)
                     {
                         return(new ZeroOrMore(subPath));
                     }
                     else
                     {                                           // -2
                         return(new NOrMore(subPath, (int)min)); // TODO: is this correct?
                     }
                 }
                 else
                 {
                     if (min == null || min == -1)
                     {
                         return(new ZeroToN(subPath, (int)max));
                     }
                     else
                     {
                         return(new NToM(subPath, (int)min, (int)max));
                     }
                 }
             }
             else if (RDFUtil.sameTerm(SP.ClassReversePath, type))
             {
                 ISparqlPath subPath = createPath(path, SP.PropertySubPath);
                 return(new InversePath(subPath));
             }
             else if (RDFUtil.sameTerm(SP.ClassSeqPath, type))
             {
                 ISparqlPath leftPath  = createPath(path, SP.PropertyPath1);
                 ISparqlPath rightPath = createPath(path, SP.PropertyPath2);
                 return(new SequencePath(leftPath, rightPath));
             }
             else if (RDFUtil.sameTerm(SP.ClassReverseLinkPath, type))
             {
                 IResource   node    = path.getObject(SP.PropertyNode);
                 ISparqlPath subPath = createPath(node); // TODO: is this correct ?
                 return(new InversePath(subPath));
             }
         }
         return(null);
     }
 }
示例#20
0
 public static bool isRootClass(IResource cls)
 {
     return(RDFUtil.sameTerm(RDFS.ClassResource, cls) || RDFUtil.sameTerm(OWL.Thing, cls));
 }
示例#21
0
 /**
  * Checks if a given INode is spin:query or a sub-property of it.
  * @param predicate  the INode to test
  * @return true if predicate is a query property
  */
 public static bool isQueryProperty(IResource predicate)
 {
     return(RDFUtil.sameTerm(SPIN.PropertyQuery, predicate) || predicate.hasProperty(RDFS.PropertySubPropertyOf, SPIN.PropertyQuery));
 }
示例#22
0
        override protected void handleTriplePattern(ITriplePattern triplePattern, Dictionary <IResource, IResource> bindings)
        {
            bool      valid   = false;
            IResource subject = triplePattern.getSubject();

            if (RDFUtil.sameTerm(SPIN.Property_this, subject))
            {
                valid = true;
            }
            else if (bindings != null)
            {
                IVariable var = SPINFactory.asVariable(subject);
                if (var != null)
                {
                    String varName = var.getName();
                    foreach (IResource argPredicate in bindings.Keys)
                    {
                        if (varName.Equals(argPredicate.Uri().ToString().Replace(SP.BASE_URI, "").Replace(SPIN.BASE_URI, "")))
                        {
                            IResource b = bindings[argPredicate];
                            if (RDFUtil.sameTerm(SPIN.Property_this, b))
                            {
                                valid = true;
                                break;
                            }
                        }
                    }
                }
            }

            if (valid)
            {
                IResource predicate = triplePattern.getPredicate();
                if (predicate != null)
                {
                    IVariable variable = SPINFactory.asVariable(predicate);
                    if (variable == null)
                    {
                        Uri uri = predicate.Uri();
                        if (uri != null)
                        {
                            properties.Add(Resource.Get(predicate, _targetModel));
                        }
                    }
                    else if (bindings != null)
                    {
                        String varName = variable.getName();
                        foreach (IResource argPredicate in bindings.Keys)
                        {
                            if (varName.Equals(argPredicate.Uri().ToString().Replace(SP.BASE_URI, "").Replace(SPIN.BASE_URI, "")))
                            {
                                IResource b = bindings[argPredicate];
                                if (b != null && b.isUri())
                                {
                                    properties.Add(Resource.Get(b, _targetModel));
                                }
                            }
                        }
                    }
                }
            }
        }
 private bool containsVar(ITriple triple)
 {
     return(RDFUtil.sameTerm(var, triple.getObject()) ||
            RDFUtil.sameTerm(var, triple.getPredicate()) ||
            RDFUtil.sameTerm(var, triple.getSubject()));
 }
示例#24
0
        // TODO Replace IEnumerable<IUpdate> with a SparqlUpdateCommandSet
        /// <summary>
        /// TODO find a way to compile the global changes so ExecutionContexts can be set globally for Rules processing or Constraints checking.
        /// </summary>
        /// <param name="spinUpdateCommandSet"></param>
        internal IGraph ExecuteUpdate(IEnumerable <IUpdate> spinUpdateCommandSet)
        {
            QueryMode currentQueryMode         = QueryExecutionMode;
            Uri       currentExecutionGraphUri = RDFRuntime.NewTempGraphUri();
            IGraph    remoteChanges            = new ThreadSafeGraph();

            remoteChanges.BaseUri = currentExecutionGraphUri;
            try
            {
                foreach (IUpdate update in spinUpdateCommandSet)
                {
                    if (update != null)
                    {
                        UpdateInternal(update, currentExecutionGraphUri);
                    }
                }
                Storage.LoadGraph(remoteChanges, currentExecutionGraphUri);

                List <Resource> newTypes = new List <Resource>();
                foreach (Triple t in remoteChanges.Triples)
                {
                    if (RDFUtil.sameTerm(RDF.PropertyType, t.Predicate))
                    {
                        // if remoteChanges contains an already checked rdf:type triple that means we have a infinite loop case in the SPIN processing pipeline so we stop execution
                        if (_loopPreventionChecks.Contains(t))
                        {
                            // TODO document better the exception cause
                            throw new SpinException("Infinite loop encountered. Execution is canceled");
                        }
                        _loopPreventionChecks.Add(t);
                        newTypes.Add(AsResource(t.Object));
                    }
                    else if (RDFUtil.sameTerm(RDFRuntime.PropertyHasChanged, t.Predicate))
                    {
                        // mark the resource as updated for the next global CheckConstraints or Apply rules
                        _changedResources.Add(t.Object);
                    }
                    else if (RDFUtil.sameTerm(RDFRuntime.PropertyResets, t.Predicate))
                    {
                        // TODO log the property resets for filtering pattern extensions in the subsequent SPARQL execution
                    }
                }
                CurrentExecutionContext = currentExecutionGraphUri;
                // run the constructors
                remoteChanges.Assert(this.RunConstructors(newTypes).Triples);
            }
            catch (Exception any)
            {
                // for cleanliness sake on exception cases
                foreach (Uri graphUri in Configuration.GetTriplesRemovalsGraphs().Union(Configuration.GetTriplesAdditionsGraphs()))
                {
                    Storage.DeleteGraph(graphUri);
                }
                throw new Exception("", any);
            }
            finally
            {
                Storage.DeleteGraph(currentExecutionGraphUri);
                _queryExecutionMode = currentQueryMode;

                ResetExecutionContext();
            }
            return(remoteChanges);
        }