Esempio n. 1
0
 /// <summary>
 /// Uri-based ctor to build a context from the given Uri
 /// </summary>
 public RDFContext(Uri ctxUri)
 {
     if (ctxUri != null)
     {
         Uri tempUri = RDFModelUtilities.GetUriFromString(ctxUri.ToString());
         if (tempUri != null)
         {
             if (!tempUri.ToString().StartsWith("bnode:", StringComparison.OrdinalIgnoreCase))
             {
                 this.Context = tempUri;
                 this.SetLazyPatternMemberID();
             }
             else
             {
                 throw new RDFStoreException("Cannot create RDFContext because given \"ctxUri\" parameter represents a blank node Uri.");
             }
         }
         else
         {
             throw new RDFStoreException("Cannot create RDFContext because given \"ctxUri\" parameter does not represent a valid Uri.");
         }
     }
     else
     {
         throw new RDFStoreException("Cannot create RDFContext because given \"ctxUri\" parameter is null.");
     }
 }
Esempio n. 2
0
 /// <summary>
 /// Uri-based ctor to build a context from the given Uri
 /// </summary>
 public RDFContext(Uri ctxUri)
 {
     if (ctxUri != null)
     {
         Uri tempUri = RDFModelUtilities.GetUriFromString(ctxUri.ToString());
         if (tempUri != null)
         {
             if (!tempUri.ToString().ToUpperInvariant().StartsWith("BNODE:"))
             {
                 this.Context         = tempUri;
                 this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString());
             }
             else
             {
                 throw new RDFStoreException("Cannot create RDFContext because given \"ctxUri\" parameter represents a blank node Uri.");
             }
         }
         else
         {
             throw new RDFStoreException("Cannot create RDFContext because given \"ctxUri\" parameter does not represent a valid Uri.");
         }
     }
     else
     {
         throw new RDFStoreException("Cannot create RDFContext because given \"ctxUri\" parameter is null.");
     }
 }
Esempio n. 3
0
        /// <summary>
        /// Checks if the given attribute is absolute Uri, relative Uri, "rdf:ID" relative Uri, "rdf:nodeID" blank node Uri
        /// </summary>
        internal static String ResolveRelativeNode(XmlAttribute attr, Uri xmlBase)
        {
            if (attr != null && xmlBase != null)
            {
                String attrValue = attr.Value;

                //"rdf:ID" relative Uri: must be resolved against the xmlBase namespace
                if (attr.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":ID", StringComparison.Ordinal) ||
                    attr.LocalName.Equals("ID", StringComparison.Ordinal))
                {
                    attrValue = RDFModelUtilities.GetUriFromString(xmlBase + attrValue).ToString();
                }

                //"rdf:nodeID" relative Uri: must be resolved against the "bnode:" prefix
                else if (attr.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":nodeID", StringComparison.Ordinal) ||
                         attr.LocalName.Equals("nodeID", StringComparison.Ordinal))
                {
                    if (!attrValue.StartsWith("bnode:"))
                    {
                        attrValue = "bnode:" + attrValue;
                    }
                }

                //"rdf:about" or "rdf:resource" relative Uri: must be resolved against the xmlBase namespace
                else if (RDFModelUtilities.GetUriFromString(attrValue) == null)
                {
                    attrValue = RDFModelUtilities.GetUriFromString(xmlBase + attrValue).ToString();
                }

                return(attrValue);
            }
            throw new RDFModelException("Cannot resolve relative node because given \"attr\" or \"xmlBase\" parameters are null");
        }
Esempio n. 4
0
 /// <summary>
 /// Uri-based ctor to build a namespace with prefix and uri
 /// </summary>
 public RDFNamespace(String prefix, Uri nSpace)
 {
     if (prefix != null && Regex.IsMatch(prefix, @"^[a-zA-Z0-9_]+$"))
     {
         if (prefix.ToUpperInvariant() != "BNODE" && prefix.ToUpperInvariant() != "XMLNS")
         {
             if (nSpace != null &&
                 !nSpace.ToString().ToUpperInvariant().StartsWith("BNODE:") &&
                 !nSpace.ToString().ToUpperInvariant().StartsWith("XMLNS:"))
             {
                 this.Prefix      = prefix;
                 this.Namespace   = RDFModelUtilities.GetUriFromString(nSpace.ToString());
                 this.NamespaceID = RDFModelUtilities.CreateHash(this.ToString());
             }
             else
             {
                 throw new RDFModelException("Cannot create RDFNamespace because \"nSpace\" parameter is null or cannot start with \"bnode\" or \"xmlns\" prefixes, because they are reserved.");
             }
         }
         else
         {
             throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter cannot be \"bnode\"or \"xmlns\", because they are reserved.");
         }
     }
     else
     {
         throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter is null or not alphanumeric.");
     }
 }
        /// <summary>
        /// Builds a namespace with given prefix and Uri
        /// </summary>
        public RDFNamespace(string prefix, string uri)
        {
            //Validate prefix: must contain only letters/numbers and cannot be "bnode" or "xmlns"
            if (!string.IsNullOrWhiteSpace(prefix))
            {
                prefix = prefix.Trim();

                if (Prefix.Match(prefix).Success)
                {
                    if (prefix.ToUpperInvariant() == "BNODE" || prefix.ToUpperInvariant() == "XMLNS")
                    {
                        throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter cannot be \"bnode\" or \"xmlns\"");
                    }
                }
                else
                {
                    throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter contains unallowed characters");
                }
            }
            else
            {
                throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter is null or empty");
            }

            //Validate uri: must be an absolute Uri and cannot start with "bnode:" or "xmlns:"
            if (!string.IsNullOrWhiteSpace(uri))
            {
                uri = uri.Trim();

                Uri finalUri = RDFModelUtilities.GetUriFromString(uri);
                if (finalUri != null)
                {
                    if (!finalUri.ToString().ToUpperInvariant().StartsWith("BNODE:") &&
                        !finalUri.ToString().ToUpperInvariant().StartsWith("XMLNS:"))
                    {
                        this.NamespacePrefix = prefix;
                        this.NamespaceUri    = finalUri;
                        this.DereferenceUri  = finalUri;
                        this.NamespaceID     = RDFModelUtilities.CreateHash(this.ToString());
                    }
                    else
                    {
                        throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter cannot start with \"bnode:\" or \"xmlns:\"");
                    }
                }
                else
                {
                    throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter is not a valid Uri");
                }
            }
            else
            {
                throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter is null or empty");
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Builds a namespace with given prefix and Uri
        /// </summary>
        public RDFNamespace(String prefix, String uri)
        {
            //Validate prefix: must contain only letters/numbers and cannot be "bnode" or "xmlns"
            if (prefix != null && prefix.Trim() != String.Empty)
            {
                prefix = prefix.Trim();

                if (Regex.IsMatch(prefix, @"^[a-zA-Z0-9_]+$"))
                {
                    if (prefix.ToUpperInvariant() == "BNODE" || prefix.ToUpperInvariant() == "XMLNS")
                    {
                        throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter cannot be \"bnode\" or \"xmlns\"");
                    }
                }
                else
                {
                    throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter contains unallowed characters");
                }
            }
            else
            {
                throw new RDFModelException("Cannot create RDFNamespace because \"prefix\" parameter is null or empty");
            }

            //Validate uri: must be an absolute Uri and cannot start with "bnode:" or "xmlns:"
            if (uri != null && uri.Trim() != String.Empty)
            {
                uri = uri.Trim();

                Uri _uri = RDFModelUtilities.GetUriFromString(uri);
                if (_uri != null)
                {
                    if (!_uri.ToString().ToUpperInvariant().StartsWith("BNODE:") && !_uri.ToString().ToUpperInvariant().StartsWith("XMLNS:"))
                    {
                        this.NamespacePrefix = prefix;
                        this.NamespaceUri    = _uri;
                        this.NamespaceID     = RDFModelUtilities.CreateHash(this.ToString());
                    }
                    else
                    {
                        throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter cannot start with \"bnode:\" or \"xmlns:\"");
                    }
                }
                else
                {
                    throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter is not a valid Uri");
                }
            }
            else
            {
                throw new RDFModelException("Cannot create RDFNamespace because \"uri\" parameter is null or empty");
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Uri-based ctor to build a non-blank resource;
 /// When given Uri starts with "bnode:" it builds a blank resource
 /// </summary>
 public RDFResource(Uri uri)
 {
     if (uri != null)
     {
         this.URI             = RDFModelUtilities.GetUriFromString(uri.ToString());
         this.IsBlank         = this.URI.ToString().StartsWith("bnode:");
         this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString());
     }
     else
     {
         throw new RDFModelException("Cannot create RDFResource because given \"uri\" parameter is null");
     }
 }
Esempio n. 8
0
        /// <summary>
        /// Applies the filter on the column corresponding to the variable in the given datarow
        /// </summary>
        internal override Boolean ApplyFilter(DataRow row, Boolean applyNegation)
        {
            Boolean keepRow = true;

            //Check is performed only if the row contains a column named like the filter's variable
            if (row.Table.Columns.Contains(this.Variable.ToString()))
            {
                //Depends on "IsLiteral" filter, because we must find numeric literals
                RDFIsLiteralFilter isLiteralFilter = new RDFIsLiteralFilter(this.Variable);
                keepRow = isLiteralFilter.ApplyFilter(row, false);

                //Successfull match if it is a literal whose value can be parsed into a "Decimal" object
                if (keepRow)
                {
                    String litVal = row[this.Variable.ToString()].ToString();

                    //Plain Literal
                    if (!litVal.Contains("^^") ||
                        litVal.EndsWith("^^") ||
                        RDFModelUtilities.GetUriFromString(litVal.Substring(litVal.LastIndexOf("^^", StringComparison.Ordinal) + 2)) == null)
                    {
                        try {
                            Decimal.Parse(litVal, CultureInfo.InvariantCulture);
                        }
                        catch {
                            keepRow = false;
                        }
                    }

                    //Typed Literal
                    else
                    {
                        try {
                            Decimal.Parse(litVal.Substring(0, litVal.LastIndexOf("^^", StringComparison.Ordinal)), CultureInfo.InvariantCulture);
                        }
                        catch {
                            keepRow = false;
                        }
                    }
                }

                //Apply the eventual negation
                if (applyNegation)
                {
                    keepRow = !keepRow;
                }
            }

            return(keepRow);
        }
Esempio n. 9
0
        /// <summary>
        /// Builds a non-blank resource (if starting with "_:" or "bnode:", it builds a blank resource)
        /// </summary>
        public RDFResource(String uriString)
        {
            Uri tempUri = RDFModelUtilities.GetUriFromString(uriString);

            if (tempUri != null)
            {
                this.URI             = tempUri;
                this.IsBlank         = this.URI.ToString().StartsWith("bnode:");
                this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString());
            }
            else
            {
                throw new RDFModelException("Cannot create RDFResource because given \"uriString\" parameter is null or cannot be converted to a valid Uri");
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Retrieves a namespace from the register by seeking presence of its Uri.
        /// If not found, and the EnablePrefixCCService configuration is true, it
        /// tries to resolve the namespace with a reverse lookup to prefix.cc service.
        /// </summary>
        public static RDFNamespace GetByNamespace(String nSpace)
        {
            Uri tempNS = RDFModelUtilities.GetUriFromString(nSpace.Trim());

            if (tempNS != null)
            {
                var result = Instance.Register.Find(ns => ns.Namespace.Equals(tempNS));
                if (result == null && EnablePrefixCCService)
                {
                    result = RDFModelUtilities.LookupPrefixCC(nSpace.Trim(), 2);
                }
                return(result);
            }
            return(null);
        }
Esempio n. 11
0
        /// <summary>
        /// Parses the current quadruple of the data reader
        /// </summary>
        internal static RDFQuadruple ParseQuadruple(IDataReader fetchedQuadruples)
        {
            if (fetchedQuadruples != null)
            {
                RDFContext  qContext   = new RDFContext(fetchedQuadruples["Context"].ToString());
                RDFResource qSubject   = new RDFResource(fetchedQuadruples["Subject"].ToString());
                RDFResource qPredicate = new RDFResource(fetchedQuadruples["Predicate"].ToString());

                //SPO-flavour quadruple
                if (fetchedQuadruples["TripleFlavor"].ToString().Equals("1"))
                {
                    RDFResource qObject = new RDFResource(fetchedQuadruples["Object"].ToString());
                    return(new RDFQuadruple(qContext, qSubject, qPredicate, qObject));
                }

                //SPL-flavour quadruple
                string literal = fetchedQuadruples["Object"].ToString();

                //PlainLiteral
                int lastIndexOfDatatype = literal.LastIndexOf("^^", StringComparison.OrdinalIgnoreCase);
                int lastIndexOfLanguage = literal.LastIndexOf("@", StringComparison.OrdinalIgnoreCase);
                if (!literal.Contains("^^") ||
                    literal.EndsWith("^^") ||
                    RDFModelUtilities.GetUriFromString(literal.Substring(lastIndexOfDatatype + 2)) == null)
                {
                    RDFPlainLiteral pLit = null;
                    if (RDFNTriples.regexLPL.Match(literal).Success)
                    {
                        string pLitValue = literal.Substring(0, lastIndexOfLanguage);
                        string pLitLang  = literal.Substring(lastIndexOfLanguage + 1);
                        pLit = new RDFPlainLiteral(pLitValue, pLitLang);
                    }
                    else
                    {
                        pLit = new RDFPlainLiteral(literal);
                    }
                    return(new RDFQuadruple(qContext, qSubject, qPredicate, pLit));
                }

                //TypedLiteral
                string tLitValue                = literal.Substring(0, lastIndexOfDatatype);
                string tLitDatatype             = literal.Substring(lastIndexOfDatatype + 2);
                RDFModelEnums.RDFDatatypes dt   = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
                RDFTypedLiteral            tLit = new RDFTypedLiteral(tLitValue, dt);
                return(new RDFQuadruple(qContext, qSubject, qPredicate, tLit));
            }
            throw new RDFStoreException("Cannot parse quadruple because given \"fetchedQuadruples\" parameter is null.");
        }
Esempio n. 12
0
        /// <summary>
        /// Parses the given string to return an instance of pattern member
        /// </summary>
        internal static RDFPatternMember ParseRDFPatternMember(string pMember)
        {
            if (pMember == null)
            {
                throw new RDFQueryException("Cannot parse pattern member because given \"pMember\" parameter is null.");
            }

            #region Uri
            if (Uri.TryCreate(pMember, UriKind.Absolute, out _))
            {
                return(new RDFResource(pMember));
            }
            #endregion

            #region Plain Literal
            int lastIndexOfDatatype = pMember.LastIndexOf("^^", StringComparison.OrdinalIgnoreCase);
            int lastIndexOfLanguage = pMember.LastIndexOf("@", StringComparison.OrdinalIgnoreCase);
            if (!pMember.Contains("^^") ||
                pMember.EndsWith("^^") ||
                RDFModelUtilities.GetUriFromString(pMember.Substring(lastIndexOfDatatype + 2)) == null)
            {
                RDFPlainLiteral pLit = null;
                if (RDFNTriples.regexLPL.Match(pMember).Success)
                {
                    string pLitVal = pMember.Substring(0, lastIndexOfLanguage);
                    string pLitLng = pMember.Substring(lastIndexOfLanguage + 1);
                    pLit = new RDFPlainLiteral(pLitVal, pLitLng);
                }
                else
                {
                    pLit = new RDFPlainLiteral(pMember);
                }
                return(pLit);
            }
            #endregion

            #region Typed Literal
            string tLitValue                = pMember.Substring(0, lastIndexOfDatatype);
            string tLitDatatype             = pMember.Substring(lastIndexOfDatatype + 2);
            RDFModelEnums.RDFDatatypes dt   = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
            RDFTypedLiteral            tLit = new RDFTypedLiteral(tLitValue, dt);
            return(tLit);

            #endregion
        }
Esempio n. 13
0
        /// <summary>
        /// Deserializes the given TriX stream to a memory store.
        /// </summary>
        internal static RDFMemoryStore Deserialize(Stream inputStream)
        {
            try
            {
                #region deserialize
                RDFMemoryStore result = new RDFMemoryStore();
                Dictionary <Int64, RDFGraph> graphs = new Dictionary <Int64, RDFGraph>();
                using (StreamReader streamReader = new StreamReader(inputStream, Encoding.UTF8))
                {
                    using (XmlTextReader trixReader = new XmlTextReader(streamReader))
                    {
                        trixReader.DtdProcessing = DtdProcessing.Parse;
                        trixReader.Normalization = false;

                        #region document
                        XmlDocument trixDoc = new XmlDocument();
                        trixDoc.Load(trixReader);
                        #endregion

                        #region graph
                        if (trixDoc.DocumentElement != null)
                        {
                            #region graphs extraction
                            var graphEnum = trixDoc.DocumentElement.ChildNodes.GetEnumerator();
                            while (graphEnum != null && graphEnum.MoveNext())
                            {
                                XmlNode graph = (XmlNode)graphEnum.Current;
                                if (!graph.Name.Equals("graph", StringComparison.Ordinal))
                                {
                                    throw new RDFModelException(" a \"<graph>\" element was expected, instead of unrecognized \"<" + graph.Name + ">\".");
                                }
                                Uri   graphUri = RDFNamespaceRegister.DefaultNamespace.NamespaceUri;
                                Int64 graphID  = RDFNamespaceRegister.DefaultNamespace.NamespaceID;
                                if (!graphs.ContainsKey(graphID))
                                {
                                    graphs.Add(graphID, new RDFGraph().SetContext(graphUri));
                                }

                                #region triple
                                var encodedUris = 0;
                                var tripleEnum  = graph.ChildNodes.GetEnumerator();
                                while (tripleEnum != null && tripleEnum.MoveNext())
                                {
                                    XmlNode triple = (XmlNode)tripleEnum.Current;

                                    #region uri
                                    if (triple.Name.Equals("uri", StringComparison.Ordinal))
                                    {
                                        encodedUris++;
                                        if (encodedUris > 1)
                                        {
                                            throw new RDFModelException(" given file encodes a graph with more than one \"<uri>\" element.");
                                        }

                                        graphUri = RDFModelUtilities.GetUriFromString(triple.ChildNodes[0].InnerText);
                                        graphID  = RDFModelUtilities.CreateHash(graphUri.ToString());
                                        if (!graphs.ContainsKey(graphID))
                                        {
                                            graphs.Add(graphID, new RDFGraph().SetContext(graphUri));
                                        }
                                    }
                                    #endregion

                                    #region triple
                                    else if (triple.Name.Equals("triple", StringComparison.Ordinal) && triple.ChildNodes.Count == 3)
                                    {
                                        #region subj
                                        //Subject is a resource ("<uri>") or a blank node ("<id>")
                                        if (triple.ChildNodes[0].Name.Equals("uri", StringComparison.Ordinal) ||
                                            triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal))
                                        {
                                            //Sanitize eventual blank node value
                                            if (triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal))
                                            {
                                                if (!triple.ChildNodes[0].InnerText.StartsWith("bnode:"))
                                                {
                                                    triple.ChildNodes[0].InnerText = "bnode:" + triple.ChildNodes[0].InnerText.Replace("_:", String.Empty);
                                                }
                                            }
                                        }
                                        //Subject is not valid: exception must be raised
                                        else
                                        {
                                            throw new RDFModelException("subject (" + triple.ChildNodes[0].Name + ") of \"<triple>\" element is neither \"<uri>\" or \"<id>\".");
                                        }
                                        #endregion

                                        #region pred
                                        //Predicate is not valid: exception must be raised
                                        if (!triple.ChildNodes[1].Name.Equals("uri", StringComparison.Ordinal))
                                        {
                                            throw new RDFModelException("predicate (" + triple.ChildNodes[1].Name + ") of \"<triple>\" element must be \"<uri>\".");
                                        }
                                        #endregion

                                        #region object
                                        //Object is a resource ("<uri>") or a blank node ("<id>")
                                        if (triple.ChildNodes[2].Name.Equals("uri", StringComparison.Ordinal) ||
                                            triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal))
                                        {
                                            //Sanitize eventual blank node value
                                            if (triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal))
                                            {
                                                if (!triple.ChildNodes[2].InnerText.StartsWith("bnode:"))
                                                {
                                                    triple.ChildNodes[2].InnerText = "bnode:" + triple.ChildNodes[2].InnerText.Replace("_:", String.Empty);
                                                }
                                            }
                                            graphs[graphID].AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                    new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                    new RDFResource(triple.ChildNodes[2].InnerText)));
                                        }
                                        #endregion

                                        #region literal

                                        #region plain literal
                                        else if (triple.ChildNodes[2].Name.Equals("plainLiteral"))
                                        {
                                            if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0)
                                            {
                                                XmlAttribute xmlLang = triple.ChildNodes[2].Attributes[RDFVocabulary.XML.PREFIX + ":lang"];
                                                if (xmlLang != null)
                                                {
                                                    //Plain literal with language
                                                    graphs[graphID].AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                            new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                            new RDFPlainLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)), xmlLang.Value)));
                                                }
                                                else
                                                {
                                                    //Plain literal without language
                                                    graphs[graphID].AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                            new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                            new RDFPlainLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)))));
                                                }
                                            }
                                            else
                                            {
                                                //Plain literal without language
                                                graphs[graphID].AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                        new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                        new RDFPlainLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)))));
                                            }
                                        }
                                        #endregion

                                        #region typed literal
                                        else if (triple.ChildNodes[2].Name.Equals("typedLiteral", StringComparison.Ordinal))
                                        {
                                            if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0)
                                            {
                                                XmlAttribute rdfDtype = triple.ChildNodes[2].Attributes["datatype"];
                                                if (rdfDtype != null)
                                                {
                                                    graphs[graphID].AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                            new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                            new RDFTypedLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)), RDFModelUtilities.GetDatatypeFromString(rdfDtype.Value))));
                                                }
                                                else
                                                {
                                                    throw new RDFModelException(" found typed literal without required \"datatype\" attribute.");
                                                }
                                            }
                                            else
                                            {
                                                throw new RDFModelException(" found typed literal without required \"datatype\" attribute.");
                                            }
                                        }
                                        #endregion

                                        #endregion

                                        #region exception
                                        //Object is not valid: exception must be raised
                                        else
                                        {
                                            throw new RDFModelException("object (" + triple.ChildNodes[2].Name + ") of \"<triple>\" element is neither \"<uri>\" or \"<id>\" or \"<plainLiteral>\" or \"<typedLiteral>\".");
                                        }
                                        #endregion
                                    }
                                    #endregion

                                    #region exception
                                    else
                                    {
                                        throw new RDFModelException("found a TriX element (" + triple.Name + ") which is neither \"<uri>\" or \"<triple>\", or is a \"<triple>\" without the required 3 childs.");
                                    }
                                    #endregion
                                }
                                #endregion
                            }
                            #endregion

                            #region graphs merging
                            foreach (var graph in graphs)
                            {
                                result.MergeGraph(graph.Value);
                            }
                            #endregion
                        }
                        #endregion
                    }
                }
                return(result);

                #endregion
            }
            catch (Exception ex)
            {
                throw new RDFModelException("Cannot deserialize TriX because: " + ex.Message, ex);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Reads the given "SPARQL Query Results XML Format" stream into a SELECT query result
        /// </summary>
        public static RDFSelectQueryResult FromSparqlXmlResult(Stream inputStream)
        {
            try {
                #region deserialize
                RDFSelectQueryResult result = new RDFSelectQueryResult();
                using (StreamReader streamReader = new StreamReader(inputStream, Encoding.UTF8)) {
                    using (XmlTextReader xmlReader = new XmlTextReader(streamReader)) {
                        xmlReader.DtdProcessing = DtdProcessing.Parse;
                        xmlReader.Normalization = false;

                        #region document
                        XmlDocument srxDoc = new XmlDocument();
                        srxDoc.Load(xmlReader);
                        #endregion

                        #region results
                        Boolean foundHead    = false;
                        Boolean foundResults = false;
                        var     nodesEnum    = srxDoc.DocumentElement.ChildNodes.GetEnumerator();
                        while (nodesEnum != null && nodesEnum.MoveNext())
                        {
                            XmlNode node = (XmlNode)nodesEnum.Current;

                            #region HEAD
                            if (node.Name.ToUpperInvariant().Equals("HEAD", StringComparison.Ordinal))
                            {
                                foundHead = true;
                                if (node.HasChildNodes)
                                {
                                    var variablesEnum = node.ChildNodes.GetEnumerator();
                                    while (variablesEnum != null && variablesEnum.MoveNext())
                                    {
                                        #region VARIABLE
                                        XmlNode varNode = (XmlNode)variablesEnum.Current;
                                        if (varNode.Name.ToUpperInvariant().Equals("VARIABLE", StringComparison.Ordinal))
                                        {
                                            if (varNode.Attributes.Count > 0)
                                            {
                                                XmlAttribute varAttr = varNode.Attributes["name"];
                                                if (varAttr != null && varAttr.Value != String.Empty)
                                                {
                                                    RDFQueryUtilities.AddColumn(result.SelectResults, varAttr.Value);
                                                }
                                                else
                                                {
                                                    throw new Exception("one \"variable\" node was found without, or with empty, \"name\" attribute.");
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception("one \"variable\" node was found without attributes.");
                                            }
                                        }
                                        #endregion
                                    }
                                }
                                else
                                {
                                    throw new Exception("\"head\" node was found without children.");
                                }
                            }
                            #endregion

                            #region RESULTS
                            else if (node.Name.ToUpperInvariant().Equals("RESULTS", StringComparison.Ordinal))
                            {
                                foundResults = true;
                                if (foundHead)
                                {
                                    var resultsEnum = node.ChildNodes.GetEnumerator();
                                    while (resultsEnum != null && resultsEnum.MoveNext())
                                    {
                                        XmlNode resNode = (XmlNode)resultsEnum.Current;

                                        #region RESULT
                                        if (resNode.Name.ToUpperInvariant().Equals("RESULT", StringComparison.Ordinal))
                                        {
                                            if (resNode.HasChildNodes)
                                            {
                                                var results = new Dictionary <String, String>();
                                                var bdgEnum = resNode.ChildNodes.GetEnumerator();
                                                while (bdgEnum != null && bdgEnum.MoveNext())
                                                {
                                                    XmlNode bdgNode  = (XmlNode)bdgEnum.Current;
                                                    Boolean foundUri = false;
                                                    Boolean foundLit = false;

                                                    #region BINDING
                                                    if (bdgNode.Name.ToUpperInvariant().Equals("BINDING", StringComparison.Ordinal))
                                                    {
                                                        if (bdgNode.Attributes != null && bdgNode.Attributes.Count > 0)
                                                        {
                                                            XmlAttribute varAttr = bdgNode.Attributes["name"];
                                                            if (varAttr != null && varAttr.Value != String.Empty)
                                                            {
                                                                if (bdgNode.HasChildNodes)
                                                                {
                                                                    #region URI / BNODE
                                                                    if (bdgNode.FirstChild.Name.ToUpperInvariant().Equals("URI", StringComparison.Ordinal) ||
                                                                        bdgNode.FirstChild.Name.ToUpperInvariant().Equals("BNODE", StringComparison.Ordinal))
                                                                    {
                                                                        foundUri = true;
                                                                        if (RDFModelUtilities.GetUriFromString(bdgNode.InnerText) != null)
                                                                        {
                                                                            results.Add(varAttr.Value, bdgNode.InnerText);
                                                                        }
                                                                        else
                                                                        {
                                                                            throw new Exception("one \"uri\" node contained data not corresponding to a valid Uri.");
                                                                        }
                                                                    }
                                                                    #endregion

                                                                    #region LITERAL
                                                                    else if (bdgNode.FirstChild.Name.ToUpperInvariant().Equals("LITERAL", StringComparison.Ordinal))
                                                                    {
                                                                        foundLit = true;
                                                                        if (bdgNode.FirstChild.Attributes != null && bdgNode.FirstChild.Attributes.Count > 0)
                                                                        {
                                                                            XmlAttribute litAttr = bdgNode.FirstChild.Attributes["datatype"];
                                                                            if (litAttr != null && litAttr.Value != String.Empty)
                                                                            {
                                                                                results.Add(varAttr.Value, bdgNode.FirstChild.InnerText + "^^" + litAttr.Value);
                                                                            }
                                                                            else
                                                                            {
                                                                                litAttr = bdgNode.FirstChild.Attributes[RDFVocabulary.XML.PREFIX + ":lang"];
                                                                                if (litAttr != null && litAttr.Value != String.Empty)
                                                                                {
                                                                                    results.Add(varAttr.Value, bdgNode.FirstChild.InnerText + "@" + litAttr.Value);
                                                                                }
                                                                                else
                                                                                {
                                                                                    throw new Exception("one \"literal\" node was found with attribute different from \"datatype\" or \"xml:lang\".");
                                                                                }
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            results.Add(varAttr.Value, bdgNode.InnerText);
                                                                        }
                                                                    }
                                                                    #endregion
                                                                }
                                                                else
                                                                {
                                                                    throw new Exception("one \"binding\" node was found without children.");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                throw new Exception("one \"binding\" node was found without, or with empty, \"name\" attribute.");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            throw new Exception("one \"binding\" node was found without attributes.");
                                                        }
                                                    }
                                                    #endregion

                                                    if (!foundUri && !foundLit)
                                                    {
                                                        throw new Exception("one \"binding\" node was found without mandatory child \"uri\" or \"literal\".");
                                                    }
                                                }
                                                RDFQueryUtilities.AddRow(result.SelectResults, results);
                                            }
                                        }
                                        #endregion
                                    }
                                }
                                else
                                {
                                    throw new Exception("\"head\" node was not found, or was after \"results\" node.");
                                }
                            }
                            #endregion
                        }

                        if (!foundHead)
                        {
                            throw new Exception("mandatory \"head\" node was not found");
                        }
                        if (!foundResults)
                        {
                            throw new Exception("mandatory \"results\" node was not found");
                        }
                        #endregion
                    }
                }
                return(result);

                #endregion
            }
            catch (Exception ex) {
                throw new RDFQueryException("Cannot read given \"SPARQL Query Results XML Format\" source because: " + ex.Message, ex);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Deserializes the given Xml stream to a graph.
        /// </summary>
        internal static RDFGraph Deserialize(Stream inputStream)
        {
            try {
                #region deserialize
                XmlReaderSettings xrs = new XmlReaderSettings();
                xrs.IgnoreComments = true;
                xrs.DtdProcessing  = DtdProcessing.Ignore;

                RDFGraph result = new RDFGraph();
                using (XmlReader xr = XmlReader.Create(new StreamReader(inputStream, Encoding.UTF8), xrs)) {
                    #region load
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(xr);
                    #endregion

                    #region root
                    //Prepare the namespace table for the Xml selections
                    var nsMgr = new XmlNamespaceManager(new NameTable());
                    nsMgr.AddNamespace(RDFVocabulary.RDF.PREFIX, RDFVocabulary.RDF.BASE_URI);

                    //Select "rdf:RDF" root node
                    XmlNode rdfRDF = GetRdfRootNode(xmlDoc, nsMgr);
                    #endregion

                    #region prefixes
                    //Select "xmlns" attributes and try to add them to the namespace register
                    var xmlnsAttrs = GetXmlnsNamespaces(rdfRDF, nsMgr);

                    //Try to get the "xml:base" attribute, which is needed to resolve eventual relative #IDs in "rdf:about" nodes
                    //If it is not found, set it to the graph Uri
                    Uri xmlBase = null;
                    if (xmlnsAttrs != null && xmlnsAttrs.Count > 0)
                    {
                        var xmlBaseAttr = (rdfRDF.Attributes["xml:base"] ?? rdfRDF.Attributes["xmlns"]);
                        if (xmlBaseAttr != null)
                        {
                            xmlBase = RDFModelUtilities.GetUriFromString(xmlBaseAttr.Value);
                        }
                    }
                    //Always keep in synch the Context and the xmlBase
                    if (xmlBase != null)
                    {
                        result.SetContext(xmlBase);
                    }
                    else
                    {
                        xmlBase = result.Context;
                    }
                    #endregion

                    #region elements
                    //Parse resource elements, which are the childs of root node and represent the subjects
                    if (rdfRDF.HasChildNodes)
                    {
                        var subjNodesEnum = rdfRDF.ChildNodes.GetEnumerator();
                        while (subjNodesEnum != null && subjNodesEnum.MoveNext())
                        {
                            #region subj
                            //Get the current resource node
                            XmlNode     subjNode = (XmlNode)subjNodesEnum.Current;
                            RDFResource subj     = GetSubjectNode(subjNode, xmlBase, result);
                            if (subj == null)
                            {
                                continue;
                            }
                            #endregion

                            #region predObjList
                            //Parse pred elements, which are the childs of subj element
                            if (subjNode.HasChildNodes)
                            {
                                IEnumerator predNodesEnum = subjNode.ChildNodes.GetEnumerator();
                                while (predNodesEnum != null && predNodesEnum.MoveNext())
                                {
                                    //Get the current pred node
                                    RDFResource pred     = null;
                                    XmlNode     predNode = (XmlNode)predNodesEnum.Current;
                                    if (predNode.NamespaceURI == String.Empty)
                                    {
                                        pred = new RDFResource(xmlBase + predNode.LocalName);
                                    }
                                    else
                                    {
                                        pred = (predNode.LocalName.StartsWith("autoNS") ?
                                                new RDFResource(predNode.NamespaceURI) :
                                                new RDFResource(predNode.NamespaceURI + predNode.LocalName));
                                    }

                                    #region object
                                    //Check if there is a "rdf:about" or a "rdf:resource" attribute
                                    XmlAttribute rdfObject =
                                        (GetRdfAboutAttribute(predNode) ??
                                         GetRdfResourceAttribute(predNode));
                                    if (rdfObject != null)
                                    {
                                        //Attribute found, but we must check if it is "rdf:ID", "rdf:nodeID" or a relative Uri
                                        String      rdfObjectValue = ResolveRelativeNode(rdfObject, xmlBase);
                                        RDFResource obj            = new RDFResource(rdfObjectValue);
                                        result.AddTriple(new RDFTriple(subj, pred, obj));
                                        continue;
                                    }
                                    #endregion

                                    #region typed literal
                                    //Check if there is a "rdf:datatype" attribute
                                    XmlAttribute rdfDatatype = GetRdfDatatypeAttribute(predNode);
                                    if (rdfDatatype != null)
                                    {
                                        RDFModelEnums.RDFDatatype dt   = RDFModelUtilities.GetDatatypeFromString(rdfDatatype.Value);
                                        RDFTypedLiteral           tLit = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerText), dt);
                                        result.AddTriple(new RDFTriple(subj, pred, tLit));
                                        continue;
                                    }
                                    //Check if there is a "rdf:parseType=Literal" attribute
                                    XmlAttribute parseLiteral = GetParseTypeLiteralAttribute(predNode);
                                    if (parseLiteral != null)
                                    {
                                        RDFTypedLiteral tLit = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerXml), RDFModelEnums.RDFDatatype.RDFS_LITERAL);
                                        result.AddTriple(new RDFTriple(subj, pred, tLit));
                                        continue;
                                    }
                                    #endregion

                                    #region plain literal
                                    //Check if there is a "xml:lang" attribute, or if a unique textual child
                                    XmlAttribute xmlLang = GetXmlLangAttribute(predNode);
                                    if (xmlLang != null || (predNode.HasChildNodes && predNode.ChildNodes.Count == 1 && predNode.ChildNodes[0].NodeType == XmlNodeType.Text))
                                    {
                                        RDFPlainLiteral pLit = new RDFPlainLiteral(HttpUtility.HtmlDecode(predNode.InnerText), (xmlLang != null ? xmlLang.Value : String.Empty));
                                        result.AddTriple(new RDFTriple(subj, pred, pLit));
                                        continue;
                                    }
                                    #endregion

                                    #region collection
                                    //Check if there is a "rdf:parseType=Collection" attribute
                                    XmlAttribute rdfCollect = GetParseTypeCollectionAttribute(predNode);
                                    if (rdfCollect != null)
                                    {
                                        ParseCollectionElements(xmlBase, predNode, subj, pred, result);
                                        continue;
                                    }
                                    #endregion

                                    #region container
                                    //Check if there is a "rdf:[Bag|Seq|Alt]" child node
                                    XmlNode container = GetContainerNode(predNode);
                                    if (container != null)
                                    {
                                        //Distinguish the right type of RDF container to build
                                        if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal) || container.LocalName.Equals("Bag", StringComparison.Ordinal))
                                        {
                                            ParseContainerElements(RDFModelEnums.RDFContainerType.Bag, container, subj, pred, result);
                                        }
                                        else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) || container.LocalName.Equals("Seq", StringComparison.Ordinal))
                                        {
                                            ParseContainerElements(RDFModelEnums.RDFContainerType.Seq, container, subj, pred, result);
                                        }
                                        else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal) || container.LocalName.Equals("Alt", StringComparison.Ordinal))
                                        {
                                            ParseContainerElements(RDFModelEnums.RDFContainerType.Alt, container, subj, pred, result);
                                        }
                                    }
                                    #endregion
                                }
                            }
                            #endregion
                        }
                    }
                    #endregion
                }
                return(result);

                #endregion
            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize Xml because: " + ex.Message, ex);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Deserializes the given TriX stream to a graph.
        /// </summary>
        internal static RDFGraph Deserialize(Stream inputStream)
        {
            try {
                #region deserialize
                XmlReaderSettings xrs = new XmlReaderSettings();
                xrs.IgnoreComments = true;
                xrs.DtdProcessing  = DtdProcessing.Ignore;

                RDFGraph result = new RDFGraph();
                using (XmlReader xr = XmlReader.Create(new StreamReader(inputStream, Encoding.UTF8), xrs)) {
                    #region load
                    XmlDocument trixDoc = new XmlDocument();
                    trixDoc.Load(xr);
                    #endregion

                    #region graph
                    if (trixDoc.DocumentElement != null)
                    {
                        if (trixDoc.DocumentElement.ChildNodes.Count > 1)
                        {
                            throw new Exception(" given TriX file seems to encode more than one graph.");
                        }

                        var graphEnum = trixDoc.DocumentElement.ChildNodes.GetEnumerator();
                        while (graphEnum != null && graphEnum.MoveNext())
                        {
                            XmlNode graph = (XmlNode)graphEnum.Current;
                            if (!graph.Name.Equals("graph", StringComparison.Ordinal))
                            {
                                throw new Exception(" a \"<graph>\" element was expected, instead of unrecognized \"<" + graph.Name + ">\".");
                            }

                            #region triple
                            var encodedUris = 0;
                            var tripleEnum  = graph.ChildNodes.GetEnumerator();
                            while (tripleEnum != null && tripleEnum.MoveNext())
                            {
                                XmlNode triple = (XmlNode)tripleEnum.Current;

                                #region uri
                                if (triple.Name.Equals("uri", StringComparison.Ordinal))
                                {
                                    encodedUris++;
                                    if (encodedUris > 1)
                                    {
                                        throw new Exception(" given file encodes a graph with more than one \"<uri>\" element.");
                                    }
                                    result.SetContext(RDFModelUtilities.GetUriFromString(triple.ChildNodes[0].InnerText));
                                }
                                #endregion

                                #region triple
                                else if (triple.Name.Equals("triple", StringComparison.Ordinal) && triple.ChildNodes.Count == 3)
                                {
                                    #region subj
                                    //Subject is a resource ("<uri>") or a blank node ("<id>")
                                    if (triple.ChildNodes[0].Name.Equals("uri", StringComparison.Ordinal) ||
                                        triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal))
                                    {
                                        //Sanitize eventual blank node value
                                        if (triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal))
                                        {
                                            if (!triple.ChildNodes[0].InnerText.StartsWith("bnode:"))
                                            {
                                                triple.ChildNodes[0].InnerText = "bnode:" + triple.ChildNodes[0].InnerText.Replace("_:", String.Empty);
                                            }
                                        }
                                    }
                                    //Subject is not valid: exception must be raised
                                    else
                                    {
                                        throw new RDFModelException("subject (" + triple.ChildNodes[0].Name + ") of \"<triple>\" element is neither \"<uri>\" or \"<id>\".");
                                    }
                                    #endregion

                                    #region pred
                                    //Predicate is not valid: exception must be raised
                                    if (!triple.ChildNodes[1].Name.Equals("uri", StringComparison.Ordinal))
                                    {
                                        throw new RDFModelException("predicate (" + triple.ChildNodes[1].Name + ") of \"<triple>\" element must be \"<uri>\".");
                                    }
                                    #endregion

                                    #region object
                                    //Object is a resource ("<uri>") or a blank node ("<id>")
                                    if (triple.ChildNodes[2].Name.Equals("uri", StringComparison.Ordinal) ||
                                        triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal))
                                    {
                                        //Sanitize eventual blank node value
                                        if (triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal))
                                        {
                                            if (!triple.ChildNodes[2].InnerText.StartsWith("bnode:"))
                                            {
                                                triple.ChildNodes[2].InnerText = "bnode:" + triple.ChildNodes[2].InnerText.Replace("_:", String.Empty);
                                            }
                                        }
                                        result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                       new RDFResource(triple.ChildNodes[1].InnerText),
                                                                       new RDFResource(triple.ChildNodes[2].InnerText)));
                                    }
                                    #endregion

                                    #region literal

                                    #region plain literal
                                    else if (triple.ChildNodes[2].Name.Equals("plainLiteral"))
                                    {
                                        if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0)
                                        {
                                            XmlAttribute xmlLang = triple.ChildNodes[2].Attributes[RDFVocabulary.XML.PREFIX + ":lang"];
                                            if (xmlLang != null)
                                            {
                                                //Plain literal with language
                                                result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                               new RDFResource(triple.ChildNodes[1].InnerText),
                                                                               new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText), xmlLang.Value)));
                                            }
                                            else
                                            {
                                                //Plain literal without language
                                                result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                               new RDFResource(triple.ChildNodes[1].InnerText),
                                                                               new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText))));
                                            }
                                        }
                                        else
                                        {
                                            //Plain literal without language
                                            result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                           new RDFResource(triple.ChildNodes[1].InnerText),
                                                                           new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText))));
                                        }
                                    }
                                    #endregion

                                    #region typed literal
                                    else if (triple.ChildNodes[2].Name.Equals("typedLiteral", StringComparison.Ordinal))
                                    {
                                        if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0)
                                        {
                                            XmlAttribute rdfDtype = triple.ChildNodes[2].Attributes["datatype"];
                                            if (rdfDtype != null)
                                            {
                                                result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                               new RDFResource(triple.ChildNodes[1].InnerText),
                                                                               new RDFTypedLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText), RDFModelUtilities.GetDatatypeFromString(rdfDtype.Value))));
                                            }
                                            else
                                            {
                                                throw new Exception(" found typed literal without required \"datatype\" attribute.");
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception(" found typed literal without required \"datatype\" attribute.");
                                        }
                                    }
                                    #endregion

                                    #endregion

                                    #region exception
                                    //Object is not valid: exception must be raised
                                    else
                                    {
                                        throw new RDFModelException("object (" + triple.ChildNodes[2].Name + ") of \"<triple>\" element is neither \"<uri>\" or \"<id>\" or \"<plainLiteral>\" or \"<typedLiteral>\".");
                                    }
                                    #endregion
                                }
                                #endregion

                                #region exception
                                else
                                {
                                    throw new RDFModelException("found a TriX element (" + triple.Name + ") which is neither \"<uri>\" or \"<triple>\", or is a \"<triple>\" without the required 3 childs.");
                                }
                                #endregion
                            }
                            #endregion
                        }
                    }
                    #endregion
                }
                return(result);

                #endregion
            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize TriX because: " + ex.Message, ex);
            }
        }