示例#1
0
        private static INode MakeRdfList(IRdfHandler handler, JArray list)
        {
            var rdfFirst = handler.CreateUriNode(new Uri(RdfNs + "first"));
            var rdfRest  = handler.CreateUriNode(new Uri(RdfNs + "rest"));
            var rdfNil   = handler.CreateUriNode(new Uri(RdfNs + "nil"));

            if (list == null || list.Count == 0)
            {
                return(rdfNil);
            }
            var bNodes = list.Select(x => handler.CreateBlankNode()).ToList();

            for (int ix = 0; ix < list.Count; ix++)
            {
                var subject = bNodes[ix];
                var obj     = MakeNode(handler, list[ix]);
                if (obj != null)
                {
                    handler.HandleTriple(new Triple(subject, rdfFirst, obj));
                }
                var rest = (ix + 1 < list.Count) ? bNodes[ix + 1] : (INode)rdfNil;
                handler.HandleTriple(new Triple(subject, rdfRest, rest));
            }
            return(bNodes[0]);
        }
示例#2
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();
                    }
                }
            }
        }
示例#3
0
        /// <summary>
        /// Attempts to resolve a QName or URI Token into a URI Node and produces appropriate error messages if this fails
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="t">Token to resolve</param>
        /// <returns></returns>
        /// <remarks>
        /// It is <strong>not</strong> recommended to use this overload since an <see cref="IRdfHandler">IRdfHandler</see> cannot resolve QNames
        /// </remarks>
        internal static INode TryResolveUri(IRdfHandler handler, IToken t)
        {
            switch (t.TokenType)
            {
            case Token.QNAME:
                throw new RdfException("Unable to resolve the QName since an RDF Handler does not have a Namespace Map that can be used to resolve QNames");

            case Token.URI:
                try
                {
                    String uri = Tools.ResolveUri(t.Value, String.Empty);
                    return(handler.CreateUriNode(new Uri(uri)));
                }
                catch (UriFormatException formatEx)
                {
                    throw new RdfParseException("Unable to resolve the URI '" + t.Value + "' due to the following error:\n" + formatEx.Message, t, formatEx);
                }
                catch (RdfException rdfEx)
                {
                    throw new RdfParseException("Unable to resolve the URI '" + t.Value + "' due to the following error:\n" + rdfEx.Message, t, rdfEx);
                }

            default:
                throw ParserHelper.Error("Unexpected Token '" + t.GetType().ToString() + "' encountered, expected a URI/QName Token to resolve into a URI", t);
            }
        }
示例#4
0
        private static void HandleTriple(IRdfHandler handler, string subject, string predicate, string obj, string datatype, bool isLiteral)
        {
            INode subjectNode   = (subject.StartsWith("_") ? (INode)handler.CreateBlankNode(subject.Substring(2)) : handler.CreateUriNode(new Uri(subject)));
            INode predicateNode = handler.CreateUriNode(new Uri(predicate));
            INode objNode;

            if (isLiteral)
            {
                if (datatype == "http://www.w3.org/2001/XMLSchema#boolean")
                {
                    obj = obj.ToLowerInvariant();
                }

                objNode = (datatype == null ? handler.CreateLiteralNode(obj) : handler.CreateLiteralNode(obj, new Uri(datatype)));
            }
            else
            {
                objNode = (obj.StartsWith("_") ? (INode)handler.CreateBlankNode(obj.Substring(2)) : handler.CreateUriNode(new Uri(obj)));
            }

            if (!handler.HandleTriple(new Triple(subjectNode, predicateNode, objNode)))
            {
                throw new InvalidOperationException(String.Format("Could not add triple {0} {1} {2} .", subjectNode, predicateNode, objNode));
            }
        }
示例#5
0
        /// <summary>
        /// Creates and handles a triple
        /// </summary>
        /// <param name="handler">Handler</param>
        /// <param name="subject">Subject</param>
        /// <param name="predicate">Predicate</param>
        /// <param name="obj">Object</param>
        /// <param name="datatype">Object Datatype</param>
        /// <param name="isLiteral">isLiteral Object</param>
        /// <returns>True if parsing should continue, false otherwise</returns>
        bool HandleTriple(IRdfHandler handler, string subject, string predicate, string obj, string datatype, bool isLiteral)
        {
            INode subjectNode;

            if (subject.StartsWith("_"))
            {
                string nodeId = subject.Substring(subject.IndexOf(":") + 1);
                subjectNode = handler.CreateBlankNode(nodeId);
            }
            else
            {
                subjectNode = handler.CreateUriNode(new Uri(subject));
            }

            INode predicateNode = handler.CreateUriNode(new Uri(predicate));

            INode objNode;

            if (isLiteral)
            {
                if (datatype == "http://www.w3.org/2001/XMLSchema#boolean")
                {
                    //  sometimes newtonsoft.json appears to return boolean as string True and dotNetRdf doesn't appear to recognize that
                    obj = ((string)obj).ToLowerInvariant();
                }

                objNode = (datatype == null) ? handler.CreateLiteralNode((string)obj) : handler.CreateLiteralNode((string)obj, new Uri(datatype));
            }
            else
            {
                if (obj.StartsWith("_"))
                {
                    string nodeId = obj.Substring(obj.IndexOf(":") + 1);
                    objNode = handler.CreateBlankNode(nodeId);
                }
                else
                {
                    objNode = handler.CreateUriNode(new Uri(obj));
                }
            }

            return(handler.HandleTriple(new Triple(subjectNode, predicateNode, objNode)));
        }
示例#6
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).ToList())
                {
                    if (t.Object.NodeType == NodeType.Blank)
                    {
                        if (!expandedBNodes.Contains(t.Object))
                        {
                            bnodes.Enqueue(t.Object);
                        }
                    }
                    if (!handler.HandleTriple((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).ToList())
                    {
                        if (!handler.HandleTriple((RewriteDescribeBNodes(t2, bnodeMapping, handler))))
                        {
                            ParserHelper.Stop();
                        }
                    }
                }
            }
        }
示例#7
0
 /// <summary>
 /// Tries to parse a URI.
 /// </summary>
 /// <param name="handler">RDF Handler.</param>
 /// <param name="uri">URI.</param>
 /// <returns>URI Node if parsed successfully.</returns>
 private static INode TryParseUri(IRdfHandler handler, String uri)
 {
     try
     {
         IUriNode n = handler.CreateUriNode(UriFactory.Create(uri));
         if (!n.Uri.IsAbsoluteUri)
         {
             throw new RdfParseException("NQuads does not permit relative URIs");
         }
         return(n);
     }
     catch (UriFormatException uriEx)
     {
         throw new RdfParseException("Invalid URI encountered, see inner exception for details", uriEx);
     }
 }
示例#8
0
        void IXmlNodeProcessor <INode> .ProcessDocumentType(string publicId, string systemId, string internalSubset, bool useAsNamespace, INode baseNode, ref INode defaultNamespace)
        {
            INode baseType = null;

            if (publicId != null)
            {
                var publicNode = rdf.CreateUriNode(UriTools.CreatePublicId(publicId));
                rdf.HandleTriple(publicNode, label, rdf.CreateLiteralNode(publicId, xpublic));
                if (systemId != null)
                {
                    rdf.HandleTriple(publicNode, isDefinedBy, MakeAbsoluteNode(baseNode, systemId));
                }
                if (useAsNamespace && UseDtdAsDefaultNamespace)
                {
                    defaultNamespace = defaultNamespace ?? publicNode;
                }
                baseType = publicNode;
            }
            else if (systemId != null)
            {
                var systemNode = MakeAbsoluteNode(baseNode, systemId);
                baseType = BlankNode("doctype");
                rdf.HandleTriple(baseType, isDefinedBy, systemNode);
                //if(useAsNamespace && UseDtdAsDefaultNamespace) defaultNamespace = defaultNamespace ?? systemNode;
            }
            INode subsetType = null;

            if (!String.IsNullOrWhiteSpace(internalSubset))
            {
                subsetType = rdf.CreateBlankNode("dtd");
                rdf.HandleTriple(subsetType, value, rdf.CreateLiteralNode(internalSubset));
                if (baseType != null)
                {
                    rdf.HandleTriple(subsetType, subClassOf, baseType);
                }
                baseType = subsetType;
            }
            if (baseType != null)
            {
                rdf.HandleTriple(baseNode, a, baseType);
            }
        }
示例#9
0
        private static void HandleTriple(IRdfHandler handler, string subject, string predicate, string obj, string datatype, bool isLiteral)
        {
            INode subjectNode = (subject.StartsWith("_") ? (INode)handler.CreateBlankNode(subject.Substring(2)) : handler.CreateUriNode(new Uri(subject)));
            INode predicateNode = handler.CreateUriNode(new Uri(predicate));
            INode objNode;
            if (isLiteral)
            {
                if (datatype == "http://www.w3.org/2001/XMLSchema#boolean")
                {
                    obj = obj.ToLowerInvariant();
                }

                objNode = (datatype == null ? handler.CreateLiteralNode(obj) : handler.CreateLiteralNode(obj, new Uri(datatype)));
            }
            else
            {
                objNode = (obj.StartsWith("_") ? (INode)handler.CreateBlankNode(obj.Substring(2)) : handler.CreateUriNode(new Uri(obj)));
            }

            if (!handler.HandleTriple(new Triple(subjectNode, predicateNode, objNode)))
            {
                throw new InvalidOperationException(String.Format("Could not add triple {0} {1} {2} .", subjectNode, predicateNode, objNode));
            }
        }
示例#10
0
        /// <summary>
        /// Creates and handles a triple
        /// </summary>
        /// <param name="handler">Handler</param>
        /// <param name="subject">Subject</param>
        /// <param name="predicate">Predicate</param>
        /// <param name="obj">Object</param>
        /// <param name="datatype">Object Datatype</param>
        /// <returns>True if parsing should continue, false otherwise</returns>
        bool HandleTriple(IRdfHandler handler, string subject, string predicate, string obj, string datatype, bool isLiteral)
        {
            INode subjectNode;
            if (subject.StartsWith("_"))
            {
                string nodeId = subject.Substring(subject.IndexOf(":") + 1);
                subjectNode = handler.CreateBlankNode(nodeId);
            }
            else
            {
                subjectNode = handler.CreateUriNode(new Uri(subject));
            }

            INode predicateNode = handler.CreateUriNode(new Uri(predicate));

            INode objNode;
            if (isLiteral)
            {
                objNode = (datatype == null) ? handler.CreateLiteralNode((string)obj) : handler.CreateLiteralNode((string)obj, new Uri(datatype));
            }
            else
            {
                if (obj.StartsWith("_"))
                {
                    string nodeId = obj.Substring(obj.IndexOf(":") + 1);
                    objNode = handler.CreateBlankNode(nodeId);
                }
                else
                {
                    objNode = handler.CreateUriNode(new Uri(obj));
                }
            }

            return handler.HandleTriple(new Triple(subjectNode, predicateNode, objNode));
        }
        /// <summary>
        /// Creates and handles a triple
        /// </summary>
        /// <param name="handler">Handler</param>
        /// <param name="subject">Subject</param>
        /// <param name="predicate">Predicate</param>
        /// <param name="obj">Object</param>
        /// <param name="datatype">Object Datatype</param>
        /// <param name="isLiteral">isLiteral Object</param>
        /// <returns>True if parsing should continue, false otherwise</returns>
        bool HandleTriple(IRdfHandler handler, string subject, string predicate, string obj, string datatype, bool isLiteral)
        {
            INode subjectNode;
            if (subject.StartsWith("_"))
            {
                string nodeId = subject.Substring(subject.IndexOf(":") + 1);
                subjectNode = handler.CreateBlankNode(nodeId);
            }
            else
            {
                subjectNode = handler.CreateUriNode(new Uri(subject));
            }

            INode predicateNode = handler.CreateUriNode(new Uri(predicate));
            
            INode objNode;
            if (isLiteral)
            {
                if (datatype == "http://www.w3.org/2001/XMLSchema#boolean")
                {
                    //  sometimes newtonsoft.json appears to return boolean as string True and dotNetRdf doesn't appear to recognize that
                    obj = ((string)obj).ToLowerInvariant();
                }

                objNode = (datatype == null) ? handler.CreateLiteralNode((string)obj) : handler.CreateLiteralNode((string)obj, new Uri(datatype));
            }
            else
            {
                if (obj.StartsWith("_"))
                {
                    string nodeId = obj.Substring(obj.IndexOf(":") + 1);
                    objNode = handler.CreateBlankNode(nodeId);
                }
                else
                {
                    objNode = handler.CreateUriNode(new Uri(obj));
                }
            }

            return handler.HandleTriple(new Triple(subjectNode, predicateNode, objNode));
        }
示例#12
0
        private INode TryParseNode(XmlReader reader, IRdfHandler handler, TripleSegment segment)
        {
            //Only need to Read() if getting the Subject
            //The previous calls will have resulted in us already reading to the start element for this node
            if (segment == TripleSegment.Subject)
            {
                reader.Read();
            }

            if (reader.NodeType != XmlNodeType.Element)
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    throw Error("Unexpected end element while trying to parse the nodes of a <triple> element", reader);
                }
            }

            if (reader.Name.Equals("uri"))
            {
                return(handler.CreateUriNode(new Uri(reader.ReadInnerXml())));
            }
            else if (reader.Name.Equals("id"))
            {
                if (segment == TripleSegment.Predicate)
                {
                    throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <uri> element as the Predicate of a Triple", reader);
                }

                return(handler.CreateBlankNode(reader.ReadInnerXml()));
            }
            else if (reader.Name.Equals("plainLiteral"))
            {
                if (segment == TripleSegment.Subject)
                {
                    throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <id>/<uri> element as the Subject of a Triple", reader);
                }

                if (reader.AttributeCount > 0)
                {
                    String lang = String.Empty;
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToNextAttribute();
                        if (reader.Name.Equals("xml:lang"))
                        {
                            lang = reader.Value;
                        }
                    }
                    reader.MoveToContent();
                    if (!lang.Equals(String.Empty))
                    {
                        return(handler.CreateLiteralNode(reader.ReadElementContentAsString(), lang));
                    }
                    else
                    {
                        return(handler.CreateLiteralNode(reader.ReadElementContentAsString()));
                    }
                }
                else
                {
                    return(handler.CreateLiteralNode(reader.ReadElementContentAsString()));
                }
            }
            else if (reader.Name.Equals("typedLiteral"))
            {
                if (reader.AttributeCount > 0)
                {
                    Uri dtUri = null;
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToNextAttribute();
                        if (reader.Name.Equals("datatype"))
                        {
                            dtUri = new Uri(reader.Value);
                        }
                    }
                    if (dtUri == null)
                    {
                        throw Error("<typedLiteral> element does not have the required datatype attribute", reader);
                    }

                    reader.MoveToContent();
                    return(handler.CreateLiteralNode(reader.ReadInnerXml(), dtUri));
                }
                else
                {
                    throw Error("<typedLiteral> element does not have the required datatype attribute", reader);
                }
            }
            else
            {
                throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <id>/<uri>/<plainLiteral>/<typedLiteral> element as part of a Triple", reader);
            }
        }
示例#13
0
        private void TryParseTriple(XmlNode tripleEl, IRdfHandler handler, Uri graphUri)
        {
            //Verify Node Name
            if (!tripleEl.Name.Equals("triple"))
            {
                throw new RdfParseException("Unexpected Element <" + tripleEl.Name + "> encountered, only an optional <uri> element followed by zero/more <triple> elements are permitted within a <graph> element");
            }
            //Verify number of Child Nodes
            if (!tripleEl.HasChildNodes)
            {
                throw new RdfParseException("<triple> element has no child nodes - 3 child nodes are expected");
            }
            if (tripleEl.ChildNodes.Count < 3)
            {
                throw new RdfParseException("<triple> element has too few child nodes (" + tripleEl.ChildNodes.Count + ") - 3 child nodes are expected");
            }
            if (tripleEl.ChildNodes.Count > 3)
            {
                throw new RdfParseException("<triple> element has too many child nodes (" + tripleEl.ChildNodes.Count + ") - 3 child nodes are expected");
            }

            //Get the 3 Child Nodes
            XmlNode subjEl, predEl, objEl;

            subjEl = tripleEl.ChildNodes[0];
            predEl = tripleEl.ChildNodes[1];
            objEl  = tripleEl.ChildNodes[2];

            //Parse XML Nodes into RDF Nodes
            INode subj, pred, obj;

            if (subjEl.Name.Equals("uri"))
            {
                subj = handler.CreateUriNode(UriFactory.Create(subjEl.InnerText));
            }
            else if (subjEl.Name.Equals("id"))
            {
                subj = handler.CreateBlankNode(subjEl.InnerText);
            }
            else
            {
                throw Error("Unexpected element <" + subjEl.Name + "> encountered, expected a <id>/<uri> element as the Subject of a Triple", subjEl);
            }

            if (predEl.Name.Equals("uri"))
            {
                pred = handler.CreateUriNode(UriFactory.Create(predEl.InnerText));
            }
            else
            {
                throw Error("Unexpected element <" + predEl.Name + "> encountered, expected a <uri> element as the Predicate of a Triple", subjEl);
            }

            if (objEl.Name.Equals("uri"))
            {
                obj = handler.CreateUriNode(UriFactory.Create(objEl.InnerText));
            }
            else if (objEl.Name.Equals("id"))
            {
                obj = handler.CreateBlankNode(objEl.InnerText);
            }
            else if (objEl.Name.Equals("plainLiteral"))
            {
                if (objEl.Attributes.GetNamedItem("xml:lang") != null)
                {
                    obj = handler.CreateLiteralNode(objEl.InnerText, objEl.Attributes["xml:lang"].Value);
                }
                else
                {
                    obj = handler.CreateLiteralNode(objEl.InnerText);
                }
            }
            else if (objEl.Name.Equals("typedLiteral"))
            {
                if (objEl.Attributes.GetNamedItem("datatype") != null)
                {
                    Uri dtUri = UriFactory.Create(objEl.Attributes["datatype"].Value);
                    if (objEl.FirstChild.NodeType == XmlNodeType.Text)
                    {
                        obj = handler.CreateLiteralNode(objEl.InnerText, dtUri);
                    }
                    else if (objEl.FirstChild.NodeType == XmlNodeType.CDATA)
                    {
                        obj = handler.CreateLiteralNode(objEl.FirstChild.InnerXml, dtUri);
                    }
                    else
                    {
                        obj = handler.CreateLiteralNode(objEl.InnerText, dtUri);
                    }
                }
                else
                {
                    throw Error("<typedLiteral> element does not have the required datatype attribute", objEl);
                }
            }
            else
            {
                throw Error("Unexpected element <" + objEl.Name + "> encountered, expected a <id>/<uri>/<plainLiteral>/<typedLiteral> element as the Object of a Triple", subjEl);
            }

            //Assert the resulting Triple
            if (!handler.HandleTriple(new Triple(subj, pred, obj, graphUri)))
            {
                ParserHelper.Stop();
            }
            ;
        }
示例#14
0
        /// <summary>
        /// Attempts to resolve a QName or URI Token into a URI Node and produces appropriate error messages if this fails
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="t">Token to resolve</param>
        /// <returns></returns>
        /// <remarks>
        /// It is <strong>not</strong> recommended to use this overload since an <see cref="IRdfHandler">IRdfHandler</see> cannot resolve QNames
        /// </remarks>
        internal static INode TryResolveUri(IRdfHandler handler, IToken t)
        {
            switch (t.TokenType)
            {
                case Token.QNAME:
                    throw new RdfException("Unable to resolve the QName since an RDF Handler does not have a Namespace Map that can be used to resolve QNames");

                case Token.URI:
                    try
                    {
                        String uri = Tools.ResolveUri(t.Value, String.Empty);
                        return handler.CreateUriNode(new Uri(uri));
                    }
                    catch (UriFormatException formatEx)
                    {
                        throw new RdfParseException("Unable to resolve the URI '" + t.Value + "' due to the following error:\n" + formatEx.Message, t, formatEx);
                    }
                    catch (RdfException rdfEx)
                    {
                        throw new RdfParseException("Unable to resolve the URI '" + t.Value + "' due to the following error:\n" + rdfEx.Message, t, rdfEx);
                    }

                default:
                    throw ParserHelper.Error("Unexpected Token '" + t.GetType().ToString() + "' encountered, expected a URI/QName Token to resolve into a URI", t);
            }
        }
示例#15
0
        private INode TryParseNode(XmlReader reader, IRdfHandler handler, TripleSegment segment)
        {
            //Only need to Read() if getting the Subject
            //The previous calls will have resulted in us already reading to the start element for this node
            if (segment == TripleSegment.Subject) reader.Read();

            if (reader.NodeType != XmlNodeType.Element)
            {
                if (reader.NodeType == XmlNodeType.EndElement) throw Error("Unexpected end element while trying to parse the nodes of a <triple> element", reader);
            }

            if (reader.Name.Equals("uri"))
            {
               return handler.CreateUriNode(new Uri(reader.ReadInnerXml()));
            }
            else if (reader.Name.Equals("id"))
            {
                if (segment == TripleSegment.Predicate) throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <uri> element as the Predicate of a Triple", reader);

                return handler.CreateBlankNode(reader.ReadInnerXml());
            }
            else if (reader.Name.Equals("plainLiteral"))
            {
                if (segment == TripleSegment.Subject) throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <id>/<uri> element as the Subject of a Triple", reader);

                if (reader.AttributeCount > 0)
                {
                    String lang = String.Empty;
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToNextAttribute();
                        if (reader.Name.Equals("xml:lang")) lang = reader.Value;
                    }
                    reader.MoveToContent();
                    if (!lang.Equals(String.Empty))
                    {
                        return handler.CreateLiteralNode(reader.ReadInnerXml(), lang);
                    }
                    else
                    {
                        return handler.CreateLiteralNode(reader.ReadInnerXml());
                    }
                }
                else
                {
                    return handler.CreateLiteralNode(reader.ReadInnerXml());
                }
            }
            else if (reader.Name.Equals("typedLiteral"))
            {
                if (reader.AttributeCount > 0)
                {
                    Uri dtUri = null;
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToNextAttribute();
                        if (reader.Name.Equals("datatype")) dtUri = new Uri(reader.Value);
                    }
                    if (dtUri == null) throw Error("<typedLiteral> element does not have the required datatype attribute", reader);

                    reader.MoveToContent();
                    return handler.CreateLiteralNode(reader.ReadInnerXml(), dtUri);
                }
                else
                {
                    throw Error("<typedLiteral> element does not have the required datatype attribute", reader);
                }
            }
            else
            {
                throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <id>/<uri>/<plainLiteral>/<typedLiteral> element as part of a Triple", reader);
            }
        }
示例#16
0
        private void TryParseTriple(XmlNode tripleEl, IRdfHandler handler, Uri graphUri)
        {
            //Verify Node Name
            if (!tripleEl.Name.Equals("triple"))
            {
                throw new RdfParseException("Unexpected Element <" + tripleEl.Name + "> encountered, only an optional <uri> element followed by zero/more <triple> elements are permitted within a <graph> element");
            }
            //Verify number of Child Nodes
            if (!tripleEl.HasChildNodes) throw new RdfParseException("<triple> element has no child nodes - 3 child nodes are expected");
            if (tripleEl.ChildNodes.Count < 3) throw new RdfParseException("<triple> element has too few child nodes (" + tripleEl.ChildNodes.Count + ") - 3 child nodes are expected");
            if (tripleEl.ChildNodes.Count > 3) throw new RdfParseException("<triple> element has too many child nodes (" + tripleEl.ChildNodes.Count + ") - 3 child nodes are expected");

            //Get the 3 Child Nodes
            XmlNode subjEl, predEl, objEl;
            subjEl = tripleEl.ChildNodes[0];
            predEl = tripleEl.ChildNodes[1];
            objEl = tripleEl.ChildNodes[2];

            //Parse XML Nodes into RDF Nodes
            INode subj, pred, obj;
            if (subjEl.Name.Equals("uri"))
            {
                subj = handler.CreateUriNode(new Uri(subjEl.InnerText));
            }
            else if (subjEl.Name.Equals("id"))
            {
                subj = handler.CreateBlankNode(subjEl.InnerText);
            }
            else
            {
                throw Error("Unexpected element <" + subjEl.Name + "> encountered, expected a <id>/<uri> element as the Subject of a Triple", subjEl);
            }

            if (predEl.Name.Equals("uri"))
            {
                pred = handler.CreateUriNode(new Uri(predEl.InnerText));
            }
            else
            {
                throw Error("Unexpected element <" + predEl.Name + "> encountered, expected a <uri> element as the Predicate of a Triple", subjEl);
            }

            if (objEl.Name.Equals("uri"))
            {
                obj = handler.CreateUriNode(new Uri(objEl.InnerText));
            }
            else if (objEl.Name.Equals("id"))
            {
                obj = handler.CreateBlankNode(objEl.InnerText);
            }
            else if (objEl.Name.Equals("plainLiteral"))
            {
                if (objEl.Attributes.GetNamedItem("xml:lang") != null)
                {
                    obj = handler.CreateLiteralNode(objEl.InnerText, objEl.Attributes["xml:lang"].Value);
                }
                else
                {
                    obj = handler.CreateLiteralNode(objEl.InnerText);
                }
            }
            else if (objEl.Name.Equals("typedLiteral"))
            {
                if (objEl.Attributes.GetNamedItem("datatype") != null)
                {
                    Uri dtUri = new Uri(objEl.Attributes["datatype"].Value);
                    if (objEl.FirstChild.NodeType == XmlNodeType.Text)
                    {
                        obj = handler.CreateLiteralNode(objEl.InnerText, dtUri);
                    }
                    else if (objEl.FirstChild.NodeType == XmlNodeType.CDATA)
                    {
                        obj = handler.CreateLiteralNode(objEl.FirstChild.InnerXml, dtUri);
                    }
                    else
                    {
                        obj = handler.CreateLiteralNode(objEl.InnerText, dtUri);
                    }
                }
                else
                {
                    throw Error("<typedLiteral> element does not have the required datatype attribute", objEl);
                }
            }
            else
            {
                throw Error("Unexpected element <" + objEl.Name + "> encountered, expected a <id>/<uri>/<plainLiteral>/<typedLiteral> element as the Object of a Triple", subjEl);
            }

            //Assert the resulting Triple
            if (!handler.HandleTriple(new Triple(subj, pred, obj, graphUri))) throw ParserHelper.Stop(); ;
        }
示例#17
0
        private INode TryParseNode(XmlReader reader, IRdfHandler handler, TripleSegment segment)
        {
            // Only need to Read() if getting the Subject
            // The previous calls will have resulted in us already reading to the start element for this node
            if (segment == TripleSegment.Subject)
            {
                reader.Read();
            }

            ValidateNamespace(reader);

            if (reader.NamespaceURI != TriXNamespaceURI)
            {
                throw Error("Unexpected element namespace " + reader.NamespaceURI + ".", reader);
            }

            if (reader.LocalName.Equals("uri"))
            {
                return(handler.CreateUriNode(new Uri(reader.ReadInnerXml())));
            }

            if (reader.LocalName.Equals("id"))
            {
                if (segment == TripleSegment.Predicate)
                {
                    throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <uri> element as the Predicate of a Triple", reader);
                }

                return(handler.CreateBlankNode(reader.ReadInnerXml()));
            }

            if (reader.LocalName.Equals("plainLiteral"))
            {
                if (segment == TripleSegment.Subject)
                {
                    throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <id>/<uri> element as the Subject of a Triple", reader);
                }

                if (reader.AttributeCount > 0)
                {
                    var lang = string.Empty;
                    for (var i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToNextAttribute();
                        if (reader.Name.Equals("xml:lang"))
                        {
                            lang = reader.Value;
                        }
                    }
                    reader.MoveToContent();
                    if (!lang.Equals(string.Empty))
                    {
                        return(handler.CreateLiteralNode(reader.ReadElementContentAsString(), lang));
                    }

                    return(handler.CreateLiteralNode(reader.ReadElementContentAsString()));
                }

                return(handler.CreateLiteralNode(reader.ReadElementContentAsString()));
            }

            if (reader.LocalName.Equals("typedLiteral"))
            {
                if (reader.AttributeCount > 0)
                {
                    Uri dtUri = null;
                    for (var i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToNextAttribute();
                        if (reader.Name.Equals("datatype"))
                        {
                            dtUri = new Uri(reader.Value);
                        }
                    }
                    if (dtUri == null)
                    {
                        throw Error("<typedLiteral> element does not have the required datatype attribute", reader);
                    }

                    reader.MoveToContent();
                    // KA: Why ReadInnerXml here and not in other places?
                    // return handler.CreateLiteralNode(reader.ReadInnerXml(), dtUri);
                    return(handler.CreateLiteralNode(reader.ReadElementContentAsString(), dtUri));
                }

                throw Error("<typedLiteral> element does not have the required datatype attribute", reader);
            }

            throw Error("Unexpected element <" + reader.Name + "> encountered, expected a <id>/<uri>/<plainLiteral>/<typedLiteral> element as part of a Triple", reader);
        }
示例#18
0
 public static INode CreateNode(this IRdfHandler handler, Uri uri)
 {
     return(uri != null ? (INode)handler.CreateUriNode(uri) : handler.CreateBlankNode());
 }
示例#19
0
 private static INode MakeNode(IRdfHandler handler, JToken token, bool allowRelativeIri = false)
 {
     if (token is JValue)
     {
         var stringValue = token.Value <string>();
         if (JsonLdProcessor.IsBlankNodeIdentifier(stringValue))
         {
             return(handler.CreateBlankNode(stringValue.Substring(2)));
         }
         if (Uri.TryCreate(stringValue, allowRelativeIri ? UriKind.RelativeOrAbsolute : UriKind.Absolute, out Uri iri))
         {
             return(handler.CreateUriNode(iri));
         }
         return(null);
     }
     else if (JsonLdProcessor.IsValueObject(token))
     {
         string literalValue = null;
         var    valueObject  = token as JObject;
         var    value        = valueObject["@value"];
         var    datatype     = valueObject.Property("@type")?.Value.Value <string>();
         var    language     = valueObject.Property("@language")?.Value.Value <string>();
         if (value.Type == JTokenType.Boolean)
         {
             literalValue = value.Value <bool>() ? "true" : "false";
             if (datatype == null)
             {
                 datatype = XsdNs + "boolean";
             }
         }
         else if (value.Type == JTokenType.Float ||
                  value.Type == JTokenType.Integer && datatype != null && datatype.Equals(XsdNs + "double"))
         {
             literalValue = value.Value <double>().ToString("E15", CultureInfo.InvariantCulture);
             literalValue = ExponentialFormatMatcher.Replace(literalValue, "$1E");
             if (literalValue.EndsWith("E"))
             {
                 literalValue = literalValue + "0";
             }
             if (datatype == null)
             {
                 datatype = XsdNs + "double";
             }
         }
         else if (value.Type == JTokenType.Integer ||
                  value.Type == JTokenType.Float && datatype != null && datatype.Equals(XsdNs + "integer"))
         {
             literalValue = value.Value <long>().ToString("D", CultureInfo.InvariantCulture);
             if (datatype == null)
             {
                 datatype = XsdNs + "integer";
             }
         }
         else
         {
             literalValue = value.Value <string>();
             if (datatype == null && language == null)
             {
                 datatype = XsdNs + "string";
             }
         }
         return(language == null?handler.CreateLiteralNode(literalValue, new Uri(datatype)) : handler.CreateLiteralNode(literalValue, language));
     }
     else if (JsonLdProcessor.IsListObject(token))
     {
         var listArray = token["@list"] as JArray;
         return(MakeRdfList(handler, listArray));
     }
     else if ((token as JObject)?.Property("@id") != null)
     {
         // Must be a node object
         var nodeObject = (JObject)token;
         return(MakeNode(handler, nodeObject["@id"]));
     }
     return(null);
 }
示例#20
0
        /// <inheritdoc/>
        public void Load(IRdfHandler handler, TextReader input)
        {
            handler.StartRdf();
            var rdfTypeNode = handler.CreateUriNode(new Uri(RdfNs + "type"));

            try
            {
                JToken element;
                using (var reader = new JsonTextReader(input)
                {
                    DateParseHandling = DateParseHandling.None
                })
                {
                    element = JToken.ReadFrom(reader);
                }
                var expandedElement = JsonLdProcessor.Expand(element, ParserOptions);
                var nodeMap         = JsonLdProcessor.GenerateNodeMap(expandedElement);
                foreach (var p in nodeMap.Properties())
                {
                    var graphName = p.Name;
                    var graph     = p.Value as JObject;
                    if (graph == null)
                    {
                        continue;
                    }
                    Uri graphIri;
                    if (graphName == "@default")
                    {
                        graphIri = null;
                    }
                    else
                    {
                        if (!Uri.TryCreate(graphName, UriKind.Absolute, out graphIri))
                        {
                            continue;
                        }
                    }
                    foreach (var gp in graph.Properties())
                    {
                        var   subject = gp.Name;
                        var   node    = gp.Value as JObject;
                        INode subjectNode;
                        if (IsBlankNodeIdentifier(subject))
                        {
                            subjectNode = handler.CreateBlankNode(subject.Substring(2));
                        }
                        else
                        {
                            Uri subjectIri;
                            if (!Uri.TryCreate(subject, UriKind.Absolute, out subjectIri))
                            {
                                continue;
                            }
                            subjectNode = handler.CreateUriNode(subjectIri);
                        }
                        foreach (var np in node.Properties())
                        {
                            var property = np.Name;
                            var values   = np.Value as JArray;
                            if (property.Equals("@type"))
                            {
                                foreach (var type in values)
                                {
                                    var typeNode = MakeNode(handler, type);
                                    handler.HandleTriple(new Triple(subjectNode, rdfTypeNode, typeNode, graphIri));
                                }
                            }
                            else if (JsonLdProcessor.IsKeyword(property))
                            {
                                continue;
                            }
                            else if (JsonLdProcessor.IsBlankNodeIdentifier(property) && !ParserOptions.ProduceGeneralizedRdf)
                            {
                                continue;
                            }
                            else if (JsonLdProcessor.IsRelativeIri(property))
                            {
                                continue;
                            }
                            else
                            {
                                foreach (var item in values)
                                {
                                    var predicateNode = MakeNode(handler, property);
                                    var objectNode    = MakeNode(handler, item);
                                    if (objectNode != null)
                                    {
                                        handler.HandleTriple(new Triple(subjectNode, predicateNode, objectNode,
                                                                        graphIri));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                handler.EndRdf(false);
                throw;
            }
            handler.EndRdf(true);
        }
示例#21
0
        private INode MakeNode(IRdfHandler handler, JToken token, Uri graphIri, bool allowRelativeIri = false)
        {
            if (token is JValue)
            {
                var stringValue = token.Value <string>();
                if (JsonLdUtils.IsBlankNodeIdentifier(stringValue))
                {
                    return(handler.CreateBlankNode(stringValue.Substring(2)));
                }
                if (Uri.TryCreate(stringValue, allowRelativeIri ? UriKind.RelativeOrAbsolute : UriKind.Absolute, out Uri iri))
                {
                    if (!Uri.IsWellFormedUriString(stringValue, allowRelativeIri ? UriKind.RelativeOrAbsolute : UriKind.Absolute))
                    {
                        return(null);
                    }
                    return(handler.CreateUriNode(iri));
                }
                return(null);
            }

            if (JsonLdUtils.IsValueObject(token))
            {
                string literalValue = null;
                var    valueObject  = token as JObject;
                var    value        = valueObject["@value"];
                var    datatype     = valueObject.Property("@type")?.Value.Value <string>();
                var    language     = valueObject.Property("@language")?.Value.Value <string>();
                if (datatype == "@json")
                {
                    datatype = RdfNs + "JSON";
                    var serializer = new JsonLiteralSerializer();
                    literalValue = serializer.Serialize(value);
                }
                else if (value.Type == JTokenType.Boolean)
                {
                    literalValue = value.Value <bool>() ? "true" : "false";
                    if (datatype == null)
                    {
                        datatype = XsdNs + "boolean";
                    }
                }
                else if (value.Type == JTokenType.Float ||
                         value.Type == JTokenType.Integer && datatype != null && datatype.Equals(XsdNs + "double"))
                {
                    var doubleValue  = value.Value <double>();
                    var roundedValue = Math.Round(doubleValue);
                    if (doubleValue.Equals(roundedValue) && doubleValue < 1000000000000000000000.0 && datatype == null)
                    {
                        // Integer values up to 10^21 should be rendered as a fixed-point integer
                        literalValue = roundedValue.ToString("F0");
                        datatype     = XsdNs + "integer";
                    }
                    else
                    {
                        literalValue = value.Value <double>().ToString("E15", CultureInfo.InvariantCulture);
                        literalValue = ExponentialFormatMatcher.Replace(literalValue, "$1E");
                        if (literalValue.EndsWith("E"))
                        {
                            literalValue = literalValue + "0";
                        }
                        if (datatype == null)
                        {
                            datatype = XsdNs + "double";
                        }
                    }
                }
                else if (value.Type == JTokenType.Integer ||
                         value.Type == JTokenType.Float && datatype != null && datatype.Equals(XsdNs + "integer"))
                {
                    literalValue = value.Value <long>().ToString("D", CultureInfo.InvariantCulture);
                    if (datatype == null)
                    {
                        datatype = XsdNs + "integer";
                    }
                }
                else if (valueObject.ContainsKey("@direction") && ParserOptions.RdfDirection.HasValue)
                {
                    literalValue = value.Value <string>();
                    var direction = valueObject["@direction"].Value <string>();
                    language = valueObject.ContainsKey("@language")
                        ? valueObject["@language"].Value <string>().ToLowerInvariant()
                        : string.Empty;
                    if (ParserOptions.RdfDirection == JsonLdRdfDirectionMode.I18NDatatype)
                    {
                        datatype = "https://www.w3.org/ns/i18n#" + language + "_" + direction;
                        return(handler.CreateLiteralNode(literalValue, new Uri(datatype)));
                    }
                    // Otherwise direction mode is CompoundLiteral
                    var literalNode = handler.CreateBlankNode();
                    var xsdString   =
                        UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString);
                    handler.HandleTriple(new Triple(
                                             literalNode,
                                             handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfValue)),
                                             handler.CreateLiteralNode(literalValue, xsdString),
                                             graphIri));
                    if (!string.IsNullOrEmpty(language))
                    {
                        handler.HandleTriple(new Triple(
                                                 literalNode,
                                                 handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfLanguage)),
                                                 handler.CreateLiteralNode(language, xsdString),
                                                 graphIri));
                    }

                    handler.HandleTriple(new Triple(
                                             literalNode,
                                             handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfDirection)),
                                             handler.CreateLiteralNode(direction, xsdString),
                                             graphIri));

                    return(literalNode);
                }
                else
                {
                    literalValue = value.Value <string>();
                    if (datatype == null && language == null)
                    {
                        datatype = XsdNs + "string";
                    }
                }

                if (language != null)
                {
                    return(LanguageTag.IsWellFormed(language) ? handler.CreateLiteralNode(literalValue, language) : null);
                }
                return(handler.CreateLiteralNode(literalValue, new Uri(datatype)));
            }
            if (JsonLdUtils.IsListObject(token))
            {
                var listArray = token["@list"] as JArray;
                return(MakeRdfList(handler, listArray, graphIri));
            }

            if ((token as JObject)?.Property("@id") != null)
            {
                // Must be a node object
                var nodeObject = (JObject)token;
                return(MakeNode(handler, nodeObject["@id"], graphIri));
            }

            return(null);
        }