/// <summary>
 /// Sets the lazy calculation of PatternMemberID
 /// </summary>
 internal void SetLazyPatternMemberID()
 => this.LazyPatternMemberID = new Lazy <long>(() => RDFModelUtilities.CreateHash(this.ToString()));
示例#2
0
        /// <summary>
        /// Reads a graph by trying to dereference the given Uri
        /// </summary>
        public static RDFGraph FromUri(Uri uri, int timeoutMilliseconds = 20000)
        {
            RDFGraph result = new RDFGraph();

            if (uri?.IsAbsoluteUri ?? false)
            {
                Uri remappedUri = RDFModelUtilities.RemapUriForDereference(uri);
                try
                {
                    HttpWebRequest webRequest = WebRequest.CreateHttp(remappedUri);
                    webRequest.MaximumAutomaticRedirections = 3;
                    webRequest.AllowAutoRedirect            = true;
                    webRequest.Timeout = timeoutMilliseconds;
                    //RDF/XML
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "application/rdf+xml");
                    //TURTLE
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "text/turtle");
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "application/turtle");
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "application/x-turtle");
                    //N-TRIPLES
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "application/n-triples");
                    //TRIX
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "application/trix");

                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    if (webRequest.HaveResponse)
                    {
                        //RDF/XML
                        if (string.IsNullOrEmpty(webResponse.ContentType) ||
                            webResponse.ContentType.Contains("application/rdf+xml"))
                        {
                            result = FromStream(RDFModelEnums.RDFFormats.RdfXml, webResponse.GetResponseStream(), webRequest.Address);
                        }

                        //TURTLE
                        else if (webResponse.ContentType.Contains("text/turtle") ||
                                 webResponse.ContentType.Contains("application/turtle") ||
                                 webResponse.ContentType.Contains("application/x-turtle"))
                        {
                            result = FromStream(RDFModelEnums.RDFFormats.Turtle, webResponse.GetResponseStream(), webRequest.Address);
                        }

                        //N-TRIPLES
                        else if (webResponse.ContentType.Contains("application/n-triples"))
                        {
                            result = FromStream(RDFModelEnums.RDFFormats.NTriples, webResponse.GetResponseStream(), webRequest.Address);
                        }

                        //TRIX
                        else if (webResponse.ContentType.Contains("application/trix"))
                        {
                            result = FromStream(RDFModelEnums.RDFFormats.TriX, webResponse.GetResponseStream(), webRequest.Address);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new RDFModelException("Cannot read RDF graph from Uri because: " + ex.Message);
                }
            }
            else
            {
                throw new RDFModelException("Cannot read RDF graph from Uri because given \"uri\" parameter is null, or it does not represent an absolute Uri.");
            }

            return(result);
        }
示例#3
0
        /// <summary>
        /// Serializes the given store to the given filepath using N-Quads data format.
        /// </summary>
        internal static void Serialize(RDFStore store, Stream outputStream)
        {
            try
            {
                #region serialize
                using (StreamWriter sw = new StreamWriter(outputStream, Encoding.ASCII))
                {
                    String quadrupleTemplate = String.Empty;
                    foreach (var q in store.SelectAllQuadruples())
                    {
                        #region template
                        if (q.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO)
                        {
                            quadrupleTemplate = "<{SUBJ}> <{PRED}> <{OBJ}> <{CTX}> .";
                        }
                        else
                        {
                            if (q.Object is RDFPlainLiteral)
                            {
                                quadrupleTemplate = "<{SUBJ}> <{PRED}> \"{VAL}\"@{LANG} <{CTX}> .";
                            }
                            else
                            {
                                quadrupleTemplate = "<{SUBJ}> <{PRED}> \"{VAL}\"^^<{DTYPE}> <{CTX}> .";
                            }
                        }
                        #endregion

                        #region subj
                        if (((RDFResource)q.Subject).IsBlank)
                        {
                            quadrupleTemplate = quadrupleTemplate.Replace("<{SUBJ}>", RDFModelUtilities.Unicode_To_ASCII(q.Subject.ToString()).Replace("bnode:", "_:"));
                        }
                        else
                        {
                            quadrupleTemplate = quadrupleTemplate.Replace("{SUBJ}", RDFModelUtilities.Unicode_To_ASCII(q.Subject.ToString()));
                        }
                        #endregion

                        #region pred
                        quadrupleTemplate = quadrupleTemplate.Replace("{PRED}", RDFModelUtilities.Unicode_To_ASCII(q.Predicate.ToString()));
                        #endregion

                        #region object
                        if (q.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO)
                        {
                            if (((RDFResource)q.Object).IsBlank)
                            {
                                quadrupleTemplate = quadrupleTemplate.Replace("<{OBJ}>", RDFModelUtilities.Unicode_To_ASCII(q.Object.ToString())).Replace("bnode:", "_:");
                            }
                            else
                            {
                                quadrupleTemplate = quadrupleTemplate.Replace("{OBJ}", RDFModelUtilities.Unicode_To_ASCII(q.Object.ToString()));
                            }
                        }
                        #endregion

                        #region literal
                        else
                        {
                            quadrupleTemplate = quadrupleTemplate.Replace("{VAL}", RDFModelUtilities.EscapeControlCharsForXML(RDFModelUtilities.Unicode_To_ASCII(((RDFLiteral)q.Object).Value.Replace("\\", "\\\\").Replace("\"", "\\\""))));
                            quadrupleTemplate = quadrupleTemplate.Replace("\n", "\\n")
                                                .Replace("\t", "\\t")
                                                .Replace("\r", "\\r");

                            #region plain literal
                            if (q.Object is RDFPlainLiteral)
                            {
                                if (((RDFPlainLiteral)q.Object).Language != String.Empty)
                                {
                                    quadrupleTemplate = quadrupleTemplate.Replace("{LANG}", ((RDFPlainLiteral)q.Object).Language);
                                }
                                else
                                {
                                    quadrupleTemplate = quadrupleTemplate.Replace("@{LANG}", String.Empty);
                                }
                            }
                            #endregion

                            #region typed literal
                            else
                            {
                                quadrupleTemplate = quadrupleTemplate.Replace("{DTYPE}", RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)q.Object).Datatype));
                            }
                            #endregion
                        }
                        #endregion

                        #region context
                        quadrupleTemplate = quadrupleTemplate.Replace("{CTX}", RDFModelUtilities.Unicode_To_ASCII(q.Context.ToString()));
                        #endregion

                        sw.WriteLine(quadrupleTemplate);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new RDFStoreException("Cannot serialize N-Quads because: " + ex.Message, ex);
            }
        }
示例#4
0
 /// <summary>
 /// Gives the string representation of the filter
 /// </summary>
 public override String ToString()
 {
     return("FILTER ( DATATYPE(" + this.Variable + ") = <" + RDFModelUtilities.GetDatatypeFromEnum(this.Datatype) + "> )");
 }
示例#5
0
 internal override String ToString(List <RDFNamespace> prefixes)
 {
     return("FILTER ( DATATYPE(" + this.Variable + ") = " + RDFQueryPrinter.PrintPatternMember(RDFQueryUtilities.ParseRDFPatternMember(RDFModelUtilities.GetDatatypeFromEnum(this.Datatype)), prefixes) + " )");
 }
示例#6
0
        /// <summary>
        /// Prints the string representation of a pattern member
        /// </summary>
        internal static String PrintPatternMember(RDFPatternMember patternMember, List <RDFNamespace> prefixes)
        {
            if (patternMember != null)
            {
                #region Variable
                if (patternMember is RDFVariable)
                {
                    return(patternMember.ToString());
                }
                #endregion

                #region Resource/Context
                if (patternMember is RDFResource || patternMember is RDFContext)
                {
                    #region Blank
                    if (patternMember is RDFResource && ((RDFResource)patternMember).IsBlank)
                    {
                        return(patternMember.ToString().Replace("bnode:", "_:"));
                    }
                    #endregion

                    #region NonBlank
                    var abbreviatedPM = RDFQueryUtilities.AbbreviateRDFPatternMember(patternMember, prefixes);
                    if (abbreviatedPM.Item1)
                    {
                        return(abbreviatedPM.Item2);
                    }
                    else
                    {
                        return("<" + abbreviatedPM.Item2 + ">");
                    }
                    #endregion
                }
                #endregion

                #region Literal
                if (patternMember is RDFLiteral)
                {
                    #region PlainLiteral
                    if (patternMember is RDFPlainLiteral)
                    {
                        if (((RDFPlainLiteral)patternMember).Language != String.Empty)
                        {
                            return("\"" + ((RDFPlainLiteral)patternMember).Value + "\"@" + ((RDFPlainLiteral)patternMember).Language);
                        }
                        return("\"" + ((RDFPlainLiteral)patternMember).Value + "\"");
                    }
                    #endregion

                    #region TypedLiteral
                    else
                    {
                        var abbreviatedPM = RDFQueryUtilities.AbbreviateRDFPatternMember(RDFQueryUtilities.ParseRDFPatternMember(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)patternMember).Datatype)), prefixes);
                        if (abbreviatedPM.Item1)
                        {
                            return("\"" + ((RDFTypedLiteral)patternMember).Value + "\"^^" + abbreviatedPM.Item2);
                        }
                        else
                        {
                            return("\"" + ((RDFTypedLiteral)patternMember).Value + "\"^^<" + abbreviatedPM.Item2 + ">");
                        }
                    }
                    #endregion
                }
                #endregion
            }
            return(null);
        }
示例#7
0
        /// <summary>
        /// Deserializes the given TriX stream to a graph.
        /// </summary>
        internal static RDFGraph Deserialize(Stream inputStream)
        {
            try
            {
                #region deserialize
                RDFGraph result = new 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)
                        {
                            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(RDFModelUtilities.ASCII_To_Unicode(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(RDFModelUtilities.ASCII_To_Unicode(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(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)
                                                {
                                                    result.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 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);
            }
        }
示例#8
0
        /// <summary>
        /// Deserializes the given N-Triples stream to a graph.
        /// </summary>
        internal static RDFGraph Deserialize(Stream inputStream)
        {
            Int64 ntripleIndex = 0;

            try {
                #region deserialize
                using (StreamReader sr = new StreamReader(inputStream, Encoding.ASCII)) {
                    RDFGraph    result  = new RDFGraph();
                    String      ntriple = String.Empty;
                    String[]    tokens  = new String[3];
                    RDFResource S       = null;
                    RDFResource P       = null;
                    RDFResource O       = null;
                    RDFLiteral  L       = null;
                    while ((ntriple = sr.ReadLine()) != null)
                    {
                        ntripleIndex++;

                        #region sanitize  & tokenize
                        //Cleanup previous data
                        S         = null;
                        tokens[0] = String.Empty;
                        P         = null;
                        tokens[1] = String.Empty;
                        O         = null;
                        L         = null;
                        tokens[2] = String.Empty;

                        //Preliminary sanitizations: clean trailing space-like chars
                        ntriple = ntriple.Trim(new Char[] { ' ', '\t', '\r', '\n' });

                        //Skip empty or comment lines
                        if (ntriple == String.Empty || ntriple.StartsWith("#"))
                        {
                            continue;
                        }

                        //Tokenizes the sanitized triple
                        tokens = TokenizeNTriple(ntriple);
                        #endregion

                        #region subj
                        String subj = tokens[0].TrimStart(new Char[] { '<' })
                                      .TrimEnd(new   Char[] { '>' })
                                      .Replace("_:", "bnode:");
                        S = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(subj));
                        #endregion

                        #region pred
                        String pred = tokens[1].TrimStart(new Char[] { '<' })
                                      .TrimEnd(new   Char[] { '>' });
                        P = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(pred));
                        #endregion

                        #region object
                        if (tokens[2].StartsWith("<") ||
                            tokens[2].StartsWith("bnode:") ||
                            tokens[2].StartsWith("_:"))
                        {
                            String obj = tokens[2].TrimStart(new Char[] { '<' })
                                         .TrimEnd(new Char[] { '>' })
                                         .Replace("_:", "bnode:")
                                         .Trim(new Char[] { ' ', '\n', '\t', '\r' });
                            O = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(obj));
                        }
                        #endregion

                        #region literal
                        else
                        {
                            #region sanitize
                            tokens[2] = regexSqt.Replace(tokens[2], String.Empty);
                            tokens[2] = regexEqt.Replace(tokens[2], String.Empty);
                            tokens[2] = tokens[2].Replace("\\\\", "\\")
                                        .Replace("\\\"", "\"")
                                        .Replace("\\n", "\n")
                                        .Replace("\\t", "\t")
                                        .Replace("\\r", "\r");
                            tokens[2] = RDFModelUtilities.ASCII_To_Unicode(tokens[2]);
                            #endregion

                            #region plain literal
                            if (!tokens[2].Contains("^^") ||
                                tokens[2].EndsWith("^^") ||
                                tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2, 1) != "<")
                            {
                                if (regexLPL.Match(tokens[2]).Success)
                                {
                                    tokens[2] = tokens[2].Replace("\"@", "@");
                                    String pLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("@", StringComparison.Ordinal));
                                    String pLitLang  = tokens[2].Substring(tokens[2].LastIndexOf("@", StringComparison.Ordinal) + 1);
                                    L = new RDFPlainLiteral(HttpUtility.HtmlDecode(pLitValue), pLitLang);
                                }
                                else
                                {
                                    L = new RDFPlainLiteral(HttpUtility.HtmlDecode(tokens[2]));
                                }
                            }
                            #endregion

                            #region typed literal
                            else
                            {
                                tokens[2] = tokens[2].Replace("\"^^", "^^");
                                String tLitValue    = tokens[2].Substring(0, tokens[2].LastIndexOf("^^", StringComparison.Ordinal));
                                String tLitDatatype = tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2)
                                                      .TrimStart(new Char[] { '<' })
                                                      .TrimEnd(new   Char[] { '>' });
                                RDFModelEnums.RDFDatatypes dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
                                L = new RDFTypedLiteral(HttpUtility.HtmlDecode(tLitValue), dt);
                            }
                            #endregion
                        }
                        #endregion

                        #region addtriple
                        if (O != null)
                        {
                            result.AddTriple(new RDFTriple(S, P, O));
                        }
                        else
                        {
                            result.AddTriple(new RDFTriple(S, P, L));
                        }
                        #endregion
                    }
                    return(result);
                }
                #endregion
            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize N-Triples (line " + ntripleIndex + ") because: " + ex.Message, ex);
            }
        }
示例#9
0
 /// <summary>
 /// Gets the subgraph containing triples with the specified resource as predicate
 /// </summary>
 public RDFGraph SelectTriplesByPredicate(RDFResource predicateResource)
 {
     return(new RDFGraph(RDFModelUtilities.SelectTriples(this, null, predicateResource, null, null)));
 }
 /// <summary>
 /// Gives the string representation of the typed literal
 /// </summary>
 public override string ToString()
 => string.Concat(base.ToString(), "^^", RDFModelUtilities.GetDatatypeFromEnum(this.Datatype));
示例#11
0
        private static void ParseShapeConstraints(DataRow shapesRow, RDFGraph graph, RDFShape shape)
        {
            //sh:and
            if (!shapesRow.IsNull("?AND"))
            {
                RDFPatternMember reifSubj = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?AND"));
                if (reifSubj is RDFResource)
                {
                    RDFAndConstraint andConstraint = new RDFAndConstraint();
                    RDFCollection    andColl       = RDFModelUtilities.DeserializeCollectionFromGraph(graph, (RDFResource)reifSubj, RDFModelEnums.RDFTripleFlavors.SPO);
                    andColl.Items.ForEach(item => {
                        andConstraint.AddShape((RDFResource)item);
                    });
                    shape.AddConstraint(andConstraint);
                }
            }

            //sh:class
            if (!shapesRow.IsNull("?CLASS"))
            {
                RDFPatternMember cls = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?CLASS"));
                if (cls is RDFResource)
                {
                    shape.AddConstraint(new RDFClassConstraint((RDFResource)cls));
                }
            }

            //sh:closed
            if (!shapesRow.IsNull("?CLOSED"))
            {
                RDFPatternMember closed = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?CLOSED"));
                if (closed is RDFTypedLiteral &&
                    ((RDFTypedLiteral)closed).HasBooleanDatatype())
                {
                    RDFClosedConstraint closedConstraint = new RDFClosedConstraint(Boolean.Parse(((RDFTypedLiteral)closed).Value));

                    //sh:ignoredProperties
                    RDFPatternMember reifSubj = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?IGNOREDPROPERTIES"));
                    if (reifSubj is RDFResource)
                    {
                        RDFCollection ignoredPropsColl = RDFModelUtilities.DeserializeCollectionFromGraph(graph, (RDFResource)reifSubj, RDFModelEnums.RDFTripleFlavors.SPO);
                        ignoredPropsColl.Items.ForEach(item => {
                            closedConstraint.AddIgnoredProperty((RDFResource)item);
                        });
                    }

                    shape.AddConstraint(closedConstraint);
                }
            }

            //sh:datatype
            if (!shapesRow.IsNull("?DATATYPE"))
            {
                RDFPatternMember datatype = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?DATATYPE"));
                if (datatype is RDFResource)
                {
                    shape.AddConstraint(new RDFDatatypeConstraint(RDFModelUtilities.GetDatatypeFromString(datatype.ToString())));
                }
            }

            //sh:disjoint
            if (!shapesRow.IsNull("?DISJOINT"))
            {
                RDFPatternMember disjpred = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?DISJOINT"));
                if (disjpred is RDFResource)
                {
                    shape.AddConstraint(new RDFDisjointConstraint((RDFResource)disjpred));
                }
            }

            //sh:equals
            if (!shapesRow.IsNull("?EQUALS"))
            {
                RDFPatternMember eqpred = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?EQUALS"));
                if (eqpred is RDFResource)
                {
                    shape.AddConstraint(new RDFEqualsConstraint((RDFResource)eqpred));
                }
            }

            //sh:hasValue
            if (!shapesRow.IsNull("?HASVALUE"))
            {
                RDFPatternMember value = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?HASVALUE"));
                if (value is RDFResource)
                {
                    shape.AddConstraint(new RDFHasValueConstraint((RDFResource)value));
                }
                else if (value is RDFLiteral)
                {
                    shape.AddConstraint(new RDFHasValueConstraint((RDFLiteral)value));
                }
            }

            //sh:in
            if (!shapesRow.IsNull("?IN"))
            {
                RDFPatternMember reifSubj = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?IN"));
                if (reifSubj is RDFResource)
                {
                    RDFModelEnums.RDFTripleFlavors inCollFlavor = RDFModelUtilities.DetectCollectionFlavorFromGraph(graph, (RDFResource)reifSubj);
                    RDFCollection   inColl       = RDFModelUtilities.DeserializeCollectionFromGraph(graph, (RDFResource)reifSubj, inCollFlavor);
                    RDFInConstraint inConstraint = new RDFInConstraint(inColl.ItemType);
                    inColl.Items.ForEach(item => {
                        if (inColl.ItemType == RDFModelEnums.RDFItemTypes.Literal)
                        {
                            inConstraint.AddValue((RDFLiteral)item);
                        }
                        else
                        {
                            inConstraint.AddValue((RDFResource)item);
                        }
                    });
                    shape.AddConstraint(inConstraint);
                }
            }

            //sh:languageIn
            if (!shapesRow.IsNull("?LANGUAGEIN"))
            {
                RDFPatternMember reifSubj = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?LANGUAGEIN"));
                if (reifSubj is RDFResource)
                {
                    RDFCollection langTagsColl = RDFModelUtilities.DeserializeCollectionFromGraph(graph, (RDFResource)reifSubj, RDFModelEnums.RDFTripleFlavors.SPL);
                    shape.AddConstraint(new RDFLanguageInConstraint(langTagsColl.Select(x => x.ToString()).ToList()));
                }
            }

            //sh:lessThan
            if (!shapesRow.IsNull("?LESSTHAN"))
            {
                RDFPatternMember ltpred = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?LESSTHAN"));
                if (ltpred is RDFResource)
                {
                    shape.AddConstraint(new RDFLessThanConstraint((RDFResource)ltpred));
                }
            }

            //sh:lessThanOrEquals
            if (!shapesRow.IsNull("?LESSTHANOREQUALS"))
            {
                RDFPatternMember lteqpred = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?LESSTHANOREQUALS"));
                if (lteqpred is RDFResource)
                {
                    shape.AddConstraint(new RDFLessThanOrEqualsConstraint((RDFResource)lteqpred));
                }
            }

            //sh:maxCount
            if (!shapesRow.IsNull("?MAXCOUNT"))
            {
                RDFPatternMember maxCount = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MAXCOUNT"));
                if (maxCount is RDFTypedLiteral && ((RDFTypedLiteral)maxCount).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_INTEGER))
                {
                    shape.AddConstraint(new RDFMaxCountConstraint(int.Parse(((RDFTypedLiteral)maxCount).Value)));
                }
            }

            //sh:maxExclusive
            if (!shapesRow.IsNull("?MAXEXCLUSIVE"))
            {
                RDFPatternMember value = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MAXEXCLUSIVE"));
                if (value is RDFResource)
                {
                    shape.AddConstraint(new RDFMaxExclusiveConstraint((RDFResource)value));
                }
                else if (value is RDFLiteral)
                {
                    shape.AddConstraint(new RDFMaxExclusiveConstraint((RDFLiteral)value));
                }
            }

            //sh:maxInclusive
            if (!shapesRow.IsNull("?MAXINCLUSIVE"))
            {
                RDFPatternMember value = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MAXINCLUSIVE"));
                if (value is RDFResource)
                {
                    shape.AddConstraint(new RDFMaxInclusiveConstraint((RDFResource)value));
                }
                else if (value is RDFLiteral)
                {
                    shape.AddConstraint(new RDFMaxInclusiveConstraint((RDFLiteral)value));
                }
            }

            //sh:maxLength
            if (!shapesRow.IsNull("?MAXLENGTH"))
            {
                RDFPatternMember maxLength = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MAXLENGTH"));
                if (maxLength is RDFTypedLiteral && ((RDFTypedLiteral)maxLength).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_INTEGER))
                {
                    shape.AddConstraint(new RDFMaxLengthConstraint(int.Parse(((RDFTypedLiteral)maxLength).Value)));
                }
            }

            //sh:minCount
            if (!shapesRow.IsNull("?MINCOUNT"))
            {
                RDFPatternMember minCount = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MINCOUNT"));
                if (minCount is RDFTypedLiteral && ((RDFTypedLiteral)minCount).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_INTEGER))
                {
                    shape.AddConstraint(new RDFMinCountConstraint(int.Parse(((RDFTypedLiteral)minCount).Value)));
                }
            }

            //sh:minExclusive
            if (!shapesRow.IsNull("?MINEXCLUSIVE"))
            {
                RDFPatternMember value = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MINEXCLUSIVE"));
                if (value is RDFResource)
                {
                    shape.AddConstraint(new RDFMinExclusiveConstraint((RDFResource)value));
                }
                else if (value is RDFLiteral)
                {
                    shape.AddConstraint(new RDFMinExclusiveConstraint((RDFLiteral)value));
                }
            }

            //sh:minInclusive
            if (!shapesRow.IsNull("?MININCLUSIVE"))
            {
                RDFPatternMember value = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MININCLUSIVE"));
                if (value is RDFResource)
                {
                    shape.AddConstraint(new RDFMinInclusiveConstraint((RDFResource)value));
                }
                else if (value is RDFLiteral)
                {
                    shape.AddConstraint(new RDFMinInclusiveConstraint((RDFLiteral)value));
                }
            }

            //sh:minLength
            if (!shapesRow.IsNull("?MINLENGTH"))
            {
                RDFPatternMember minLength = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?MINLENGTH"));
                if (minLength is RDFTypedLiteral && ((RDFTypedLiteral)minLength).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_INTEGER))
                {
                    shape.AddConstraint(new RDFMinLengthConstraint(int.Parse(((RDFTypedLiteral)minLength).Value)));
                }
            }

            //sh:node
            if (!shapesRow.IsNull("?NODE"))
            {
                RDFPatternMember nodeshapeUri = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?NODE"));
                if (nodeshapeUri is RDFResource)
                {
                    shape.AddConstraint(new RDFNodeConstraint((RDFResource)nodeshapeUri));
                }
            }

            //sh:nodeKind
            if (!shapesRow.IsNull("?NODEKIND"))
            {
                RDFPatternMember nodeKind = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?NODEKIND"));
                if (nodeKind is RDFResource)
                {
                    if (nodeKind.Equals(RDFVocabulary.SHACL.BLANK_NODE))
                    {
                        shape.AddConstraint(new RDFNodeKindConstraint(RDFValidationEnums.RDFNodeKinds.BlankNode));
                    }
                    else if (nodeKind.Equals(RDFVocabulary.SHACL.BLANK_NODE_OR_IRI))
                    {
                        shape.AddConstraint(new RDFNodeKindConstraint(RDFValidationEnums.RDFNodeKinds.BlankNodeOrIRI));
                    }
                    else if (nodeKind.Equals(RDFVocabulary.SHACL.BLANK_NODE_OR_LITERAL))
                    {
                        shape.AddConstraint(new RDFNodeKindConstraint(RDFValidationEnums.RDFNodeKinds.BlankNodeOrLiteral));
                    }
                    else if (nodeKind.Equals(RDFVocabulary.SHACL.IRI))
                    {
                        shape.AddConstraint(new RDFNodeKindConstraint(RDFValidationEnums.RDFNodeKinds.IRI));
                    }
                    else if (nodeKind.Equals(RDFVocabulary.SHACL.IRI_OR_LITERAL))
                    {
                        shape.AddConstraint(new RDFNodeKindConstraint(RDFValidationEnums.RDFNodeKinds.IRIOrLiteral));
                    }
                    else if (nodeKind.Equals(RDFVocabulary.SHACL.LITERAL))
                    {
                        shape.AddConstraint(new RDFNodeKindConstraint(RDFValidationEnums.RDFNodeKinds.Literal));
                    }
                }
            }

            //sh:not
            if (!shapesRow.IsNull("?NOT"))
            {
                RDFPatternMember notshapeUri = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?NOT"));
                if (notshapeUri is RDFResource)
                {
                    shape.AddConstraint(new RDFNotConstraint((RDFResource)notshapeUri));
                }
            }

            //sh:or
            if (!shapesRow.IsNull("?OR"))
            {
                RDFPatternMember reifSubj = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?OR"));
                if (reifSubj is RDFResource)
                {
                    RDFOrConstraint orConstraint = new RDFOrConstraint();
                    RDFCollection   orColl       = RDFModelUtilities.DeserializeCollectionFromGraph(graph, (RDFResource)reifSubj, RDFModelEnums.RDFTripleFlavors.SPO);
                    orColl.Items.ForEach(item => {
                        orConstraint.AddShape((RDFResource)item);
                    });
                    shape.AddConstraint(orConstraint);
                }
            }

            //sh:pattern
            if (!shapesRow.IsNull("?PATTERN"))
            {
                RDFPatternMember regexPattern = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?PATTERN"));
                if (regexPattern is RDFTypedLiteral && ((RDFTypedLiteral)regexPattern).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_STRING))
                {
                    //sh:flags
                    RegexOptions regexOptions = RegexOptions.None;
                    if (!shapesRow.IsNull("?FLAGS"))
                    {
                        RDFPatternMember regexFlags = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?FLAGS"));
                        if (regexFlags is RDFTypedLiteral && ((RDFTypedLiteral)regexFlags).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_STRING))
                        {
                            if (((RDFTypedLiteral)regexFlags).Value.Contains("i"))
                            {
                                regexOptions |= RegexOptions.IgnoreCase;
                            }
                            if (((RDFTypedLiteral)regexFlags).Value.Contains("s"))
                            {
                                regexOptions |= RegexOptions.Singleline;
                            }
                            if (((RDFTypedLiteral)regexFlags).Value.Contains("m"))
                            {
                                regexOptions |= RegexOptions.Multiline;
                            }
                            if (((RDFTypedLiteral)regexFlags).Value.Contains("x"))
                            {
                                regexOptions |= RegexOptions.IgnorePatternWhitespace;
                            }
                        }
                    }
                    shape.AddConstraint(new RDFPatternConstraint(new Regex(((RDFTypedLiteral)regexPattern).Value, regexOptions)));
                }
            }

            //sh:property
            if (!shapesRow.IsNull("?PROPERTY"))
            {
                RDFPatternMember propertyshapeUri = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?PROPERTY"));
                if (propertyshapeUri is RDFResource)
                {
                    shape.AddConstraint(new RDFPropertyConstraint((RDFResource)propertyshapeUri));
                }
            }

            //sh:qualifiedValueShape
            if (!shapesRow.IsNull("?QUALIFIEDVALUESHAPE"))
            {
                RDFPatternMember qualifiedValueShapeUri = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?QUALIFIEDVALUESHAPE"));
                if (qualifiedValueShapeUri is RDFResource)
                {
                    //sh:qualifiedMinCount
                    int?qualifiedMinCountValue = null;
                    if (!shapesRow.IsNull("?QUALIFIEDMINCOUNT"))
                    {
                        RDFPatternMember qualifiedMinCount = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?QUALIFIEDMINCOUNT"));
                        if (qualifiedMinCount is RDFTypedLiteral && ((RDFTypedLiteral)qualifiedMinCount).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_INTEGER))
                        {
                            qualifiedMinCountValue = int.Parse(((RDFTypedLiteral)qualifiedMinCount).Value);
                        }
                    }
                    //sh:qualifiedMaxCount
                    int?qualifiedMaxCountValue = null;
                    if (!shapesRow.IsNull("?QUALIFIEDMAXCOUNT"))
                    {
                        RDFPatternMember qualifiedMaxCount = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?QUALIFIEDMAXCOUNT"));
                        if (qualifiedMaxCount is RDFTypedLiteral && ((RDFTypedLiteral)qualifiedMaxCount).Datatype.Equals(RDFModelEnums.RDFDatatypes.XSD_INTEGER))
                        {
                            qualifiedMaxCountValue = int.Parse(((RDFTypedLiteral)qualifiedMaxCount).Value);
                        }
                    }
                    shape.AddConstraint(new RDFQualifiedValueShapeConstraint((RDFResource)qualifiedValueShapeUri, qualifiedMinCountValue, qualifiedMaxCountValue));
                }
            }

            //sh:uniqueLang
            if (!shapesRow.IsNull("?UNIQUELANG"))
            {
                RDFPatternMember uniqueLang = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?UNIQUELANG"));
                if (uniqueLang is RDFTypedLiteral &&
                    ((RDFTypedLiteral)uniqueLang).HasBooleanDatatype())
                {
                    shape.AddConstraint(new RDFUniqueLangConstraint(Boolean.Parse(((RDFTypedLiteral)uniqueLang).Value)));
                }
            }

            //sh:xone
            if (!shapesRow.IsNull("?XONE"))
            {
                RDFPatternMember reifSubj = RDFQueryUtilities.ParseRDFPatternMember(shapesRow.Field <string>("?XONE"));
                if (reifSubj is RDFResource)
                {
                    RDFXoneConstraint xoneConstraint = new RDFXoneConstraint();
                    RDFCollection     xoneColl       = RDFModelUtilities.DeserializeCollectionFromGraph(graph, (RDFResource)reifSubj, RDFModelEnums.RDFTripleFlavors.SPO);
                    xoneColl.Items.ForEach(item => {
                        xoneConstraint.AddShape((RDFResource)item);
                    });
                    shape.AddConstraint(xoneConstraint);
                }
            }
        }
        /// <summary>
        /// Default-ctor to build a typed literal with given value and given datatype.
        /// Semantic validation of given value against given datatype is performed.
        /// </summary>
        public RDFTypedLiteral(string value, RDFModelEnums.RDFDatatypes datatype)
        {
            this.Value    = (value ?? string.Empty);
            this.Datatype = datatype;

            //Validation against semantic of given datatype
            if (RDFModelUtilities.ValidateTypedLiteral(this))
            {
                this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString());
            }
            else
            {
                throw new RDFModelException("Cannot create RDFTypedLiteral because given \"value\" parameter (" + value + ") is not well-formed against given \"datatype\" parameter (" + RDFModelUtilities.GetDatatypeFromEnum(datatype) + ")");
            }
        }
 /// <summary>
 /// Gives the string representation of the typed literal
 /// </summary>
 public override String ToString()
 {
     return(base.ToString() + "^^" + RDFModelUtilities.GetDatatypeFromEnum(this.Datatype));
 }
 internal override string ToString(List <RDFNamespace> prefixes)
 => string.Concat(
     "FILTER ( DATATYPE(", this.Variable, ") = ",
     RDFQueryPrinter.PrintPatternMember(RDFQueryUtilities.ParseRDFPatternMember(RDFModelUtilities.GetDatatypeFromEnum(this.Datatype)), prefixes), " )");
示例#15
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
                        bool foundHead    = false;
                        bool 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)
                                                {
                                                    RDFQueryEngine.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;
                                                    bool    foundUri = false;
                                                    bool    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, string.Concat(bdgNode.FirstChild.InnerText, "^^", litAttr.Value));
                                                                            }
                                                                            else
                                                                            {
                                                                                litAttr = bdgNode.FirstChild.Attributes[string.Concat(RDFVocabulary.XML.PREFIX, ":lang")];
                                                                                if (litAttr != null && litAttr.Value != string.Empty)
                                                                                {
                                                                                    results.Add(varAttr.Value, string.Concat(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\".");
                                                    }
                                                }
                                                RDFQueryEngine.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);
            }
        }
示例#16
0
 /// <summary>
 /// Gets the subgraph containing triples with the specified resource as object
 /// </summary>
 public RDFGraph SelectTriplesByObject(RDFResource objectResource)
 {
     return(new RDFGraph(RDFModelUtilities.SelectTriples(this, null, null, objectResource, null)));
 }
示例#17
0
        /// <summary>
        /// Writes the "SPARQL Query Results XML Format" stream corresponding to the SELECT query result
        /// </summary>
        public void ToSparqlXmlResult(Stream outputStream)
        {
            try
            {
                #region serialize
                using (XmlTextWriter sparqlWriter = new XmlTextWriter(outputStream, Encoding.UTF8))
                {
                    XmlDocument sparqlDoc = new XmlDocument();
                    sparqlWriter.Formatting = Formatting.Indented;

                    #region xmlDecl
                    XmlDeclaration sparqlDecl = sparqlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    sparqlDoc.AppendChild(sparqlDecl);
                    #endregion

                    #region sparqlRoot
                    XmlNode      sparqlRoot       = sparqlDoc.CreateNode(XmlNodeType.Element, "sparql", null);
                    XmlAttribute sparqlRootNS     = sparqlDoc.CreateAttribute("xmlns");
                    XmlText      sparqlRootNSText = sparqlDoc.CreateTextNode("http://www.w3.org/2005/sparql-results#");
                    sparqlRootNS.AppendChild(sparqlRootNSText);
                    sparqlRoot.Attributes.Append(sparqlRootNS);

                    #region sparqlHead
                    XmlNode     sparqlHeadElement = sparqlDoc.CreateNode(XmlNodeType.Element, "head", null);
                    IEnumerator resultColumns     = this.SelectResults.Columns.GetEnumerator();
                    while (resultColumns.MoveNext())
                    {
                        XmlNode      variableElement = sparqlDoc.CreateNode(XmlNodeType.Element, "variable", null);
                        XmlAttribute varElName       = sparqlDoc.CreateAttribute("name");
                        XmlText      varElNameText   = sparqlDoc.CreateTextNode(resultColumns.Current.ToString());
                        varElName.AppendChild(varElNameText);
                        variableElement.Attributes.Append(varElName);
                        sparqlHeadElement.AppendChild(variableElement);
                    }
                    sparqlRoot.AppendChild(sparqlHeadElement);
                    #endregion

                    #region sparqlResults
                    XmlNode     sparqlResultsElement = sparqlDoc.CreateNode(XmlNodeType.Element, "results", null);
                    IEnumerator resultRows           = this.SelectResults.Rows.GetEnumerator();
                    while (resultRows.MoveNext())
                    {
                        resultColumns.Reset();
                        XmlNode resultElement = sparqlDoc.CreateNode(XmlNodeType.Element, "result", null);
                        while (resultColumns.MoveNext())
                        {
                            if (!((DataRow)resultRows.Current).IsNull(resultColumns.Current.ToString()))
                            {
                                XmlNode      bindingElement = sparqlDoc.CreateNode(XmlNodeType.Element, "binding", null);
                                XmlAttribute bindElName     = sparqlDoc.CreateAttribute("name");
                                XmlText      bindElNameText = sparqlDoc.CreateTextNode(resultColumns.Current.ToString());
                                bindElName.AppendChild(bindElNameText);
                                bindingElement.Attributes.Append(bindElName);

                                #region RDFTerm
                                RDFPatternMember rdfTerm = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)[resultColumns.Current.ToString()].ToString());
                                if (rdfTerm is RDFResource)
                                {
                                    if (rdfTerm.ToString().StartsWith("bnode:"))
                                    {
                                        XmlNode bnodeElement = sparqlDoc.CreateNode(XmlNodeType.Element, "bnode", null);
                                        XmlText bnodeElText  = sparqlDoc.CreateTextNode(rdfTerm.ToString());
                                        bnodeElement.AppendChild(bnodeElText);
                                        bindingElement.AppendChild(bnodeElement);
                                    }
                                    else
                                    {
                                        XmlNode uriElement = sparqlDoc.CreateNode(XmlNodeType.Element, "uri", null);
                                        XmlText uriElText  = sparqlDoc.CreateTextNode(rdfTerm.ToString());
                                        uriElement.AppendChild(uriElText);
                                        bindingElement.AppendChild(uriElement);
                                    }
                                }
                                else if (rdfTerm is RDFLiteral)
                                {
                                    XmlNode litElement = sparqlDoc.CreateNode(XmlNodeType.Element, "literal", null);
                                    if (rdfTerm is RDFPlainLiteral)
                                    {
                                        if (((RDFPlainLiteral)rdfTerm).Language != string.Empty)
                                        {
                                            XmlAttribute xmlLang     = sparqlDoc.CreateAttribute(string.Concat(RDFVocabulary.XML.PREFIX, ":lang"), RDFVocabulary.XML.BASE_URI);
                                            XmlText      xmlLangText = sparqlDoc.CreateTextNode(((RDFPlainLiteral)rdfTerm).Language);
                                            xmlLang.AppendChild(xmlLangText);
                                            litElement.Attributes.Append(xmlLang);
                                        }
                                        XmlText plainLiteralText = sparqlDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)rdfTerm).Value)));
                                        litElement.AppendChild(plainLiteralText);
                                    }
                                    else
                                    {
                                        XmlAttribute datatype     = sparqlDoc.CreateAttribute("datatype");
                                        XmlText      datatypeText = sparqlDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)rdfTerm).Datatype));
                                        datatype.AppendChild(datatypeText);
                                        litElement.Attributes.Append(datatype);
                                        XmlText typedLiteralText = sparqlDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)rdfTerm).Value)));
                                        litElement.AppendChild(typedLiteralText);
                                    }
                                    bindingElement.AppendChild(litElement);
                                }
                                #endregion

                                resultElement.AppendChild(bindingElement);
                            }
                        }
                        sparqlResultsElement.AppendChild(resultElement);
                    }
                    sparqlRoot.AppendChild(sparqlResultsElement);
                    #endregion

                    sparqlDoc.AppendChild(sparqlRoot);
                    #endregion

                    sparqlDoc.Save(sparqlWriter);
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new RDFQueryException("Cannot serialize SPARQL XML RESULT because: " + ex.Message, ex);
            }
        }
示例#18
0
 /// <summary>
 /// Gets the subgraph containing triples with the specified literal as object
 /// </summary>
 public RDFGraph SelectTriplesByLiteral(RDFLiteral objectLiteral)
 {
     return(new RDFGraph(RDFModelUtilities.SelectTriples(this, null, null, null, objectLiteral)));
 }
示例#19
0
 /// <summary>
 /// Builds a blank resource
 /// </summary>
 public RDFResource()
 {
     this.URI             = new Uri("bnode:" + Guid.NewGuid());
     this.IsBlank         = true;
     this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString());
 }
 /// <summary>
 /// Default-ctor to build a plain literal without language
 /// </summary>
 public RDFPlainLiteral(string value)
 {
     this.Value           = (value ?? string.Empty);
     this.Language        = string.Empty;
     this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString());
 }
示例#21
0
        /// <summary>
        /// Serializes the given graph to the given stream using TriX data format.
        /// </summary>
        internal static void Serialize(RDFGraph graph, Stream outputStream)
        {
            try
            {
                #region serialize
                using (XmlTextWriter trixWriter = new XmlTextWriter(outputStream, Encoding.UTF8))
                {
                    XmlDocument trixDoc = new XmlDocument();
                    trixWriter.Formatting = Formatting.Indented;

                    #region xmlDecl
                    XmlDeclaration trixDecl = trixDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    trixDoc.AppendChild(trixDecl);
                    #endregion

                    #region trixRoot
                    XmlNode      trixRoot       = trixDoc.CreateNode(XmlNodeType.Element, "TriX", null);
                    XmlAttribute trixRootNS     = trixDoc.CreateAttribute("xmlns");
                    XmlText      trixRootNSText = trixDoc.CreateTextNode("http://www.w3.org/2004/03/trix/trix-1/");
                    trixRootNS.AppendChild(trixRootNSText);
                    trixRoot.Attributes.Append(trixRootNS);

                    #region graph
                    XmlNode graphElement     = trixDoc.CreateNode(XmlNodeType.Element, "graph", null);
                    XmlNode graphUriElement  = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                    XmlText graphUriElementT = trixDoc.CreateTextNode(graph.ToString());
                    graphUriElement.AppendChild(graphUriElementT);
                    graphElement.AppendChild(graphUriElement);

                    #region triple
                    foreach (var t in graph)
                    {
                        XmlNode tripleElement = trixDoc.CreateNode(XmlNodeType.Element, "triple", null);

                        #region subj
                        XmlNode subjElement = (((RDFResource)t.Subject).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null) :
                                               trixDoc.CreateNode(XmlNodeType.Element, "uri", null));
                        XmlText subjElementText = trixDoc.CreateTextNode(t.Subject.ToString());
                        subjElement.AppendChild(subjElementText);
                        tripleElement.AppendChild(subjElement);
                        #endregion

                        #region pred
                        XmlNode uriElementP = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                        XmlText uriTextP    = trixDoc.CreateTextNode(t.Predicate.ToString());
                        uriElementP.AppendChild(uriTextP);
                        tripleElement.AppendChild(uriElementP);
                        #endregion

                        #region object
                        if (t.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO)
                        {
                            XmlNode objElement = (((RDFResource)t.Object).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null) :
                                                  trixDoc.CreateNode(XmlNodeType.Element, "uri", null));
                            XmlText objElementText = trixDoc.CreateTextNode(t.Object.ToString());
                            objElement.AppendChild(objElementText);
                            tripleElement.AppendChild(objElement);
                        }
                        #endregion

                        #region literal
                        else
                        {
                            #region plain literal
                            if (t.Object is RDFPlainLiteral)
                            {
                                XmlNode plainLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "plainLiteral", null);
                                if (((RDFPlainLiteral)t.Object).Language != String.Empty)
                                {
                                    XmlAttribute xmlLang     = trixDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI);
                                    XmlText      xmlLangText = trixDoc.CreateTextNode(((RDFPlainLiteral)t.Object).Language);
                                    xmlLang.AppendChild(xmlLangText);
                                    plainLiteralElement.Attributes.Append(xmlLang);
                                }
                                XmlText plainLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value)));
                                plainLiteralElement.AppendChild(plainLiteralText);
                                tripleElement.AppendChild(plainLiteralElement);
                            }
                            #endregion

                            #region typed literal
                            else
                            {
                                XmlNode      typedLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "typedLiteral", null);
                                XmlAttribute datatype            = trixDoc.CreateAttribute("datatype");
                                XmlText      datatypeText        = trixDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)t.Object).Datatype));
                                datatype.AppendChild(datatypeText);
                                typedLiteralElement.Attributes.Append(datatype);
                                XmlText typedLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value)));
                                typedLiteralElement.AppendChild(typedLiteralText);
                                tripleElement.AppendChild(typedLiteralElement);
                            }
                            #endregion
                        }
                        #endregion

                        graphElement.AppendChild(tripleElement);
                    }
                    #endregion

                    trixRoot.AppendChild(graphElement);
                    #endregion

                    trixDoc.AppendChild(trixRoot);
                    #endregion

                    trixDoc.Save(trixWriter);
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new RDFModelException("Cannot serialize TriX because: " + ex.Message, ex);
            }
        }
示例#22
0
        /// <summary>
        /// Gets a graph representation of this constraint
        /// </summary>
        internal override RDFGraph ToRDFGraph(RDFShape shape)
        {
            RDFGraph result = new RDFGraph();

            if (shape != null)
            {
                //sh:datatype
                result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.DATATYPE, new RDFResource(RDFModelUtilities.GetDatatypeFromEnum(this.Datatype))));
            }
            return(result);
        }
示例#23
0
 /// <summary>
 /// Default-ctor to build a Distinct modifier on a query
 /// </summary>
 public RDFDistinctModifier()
 {
     this.ModifierID = RDFModelUtilities.CreateHash(this.ToString());
 }
示例#24
0
        /// <summary>
        /// Deserializes the given N-Quads stream to a memory store.
        /// </summary>
        internal static RDFMemoryStore Deserialize(Stream inputStream)
        {
            Int64 nquadIndex = 0;

            try
            {
                #region deserialize
                using (StreamReader sr = new StreamReader(inputStream, Encoding.ASCII))
                {
                    RDFMemoryStore result = new RDFMemoryStore();
                    String         nquad  = String.Empty;
                    String[]       tokens = new String[4];
                    RDFResource    S      = null;
                    RDFResource    P      = null;
                    RDFResource    O      = null;
                    RDFLiteral     L      = null;
                    RDFContext     C      = new RDFContext();
                    while ((nquad = sr.ReadLine()) != null)
                    {
                        nquadIndex++;

                        #region sanitize  & tokenize
                        //Cleanup previous data
                        S         = null;
                        tokens[0] = String.Empty;
                        P         = null;
                        tokens[1] = String.Empty;
                        O         = null;
                        L         = null;
                        tokens[2] = String.Empty;
                        C         = new RDFContext();
                        tokens[3] = String.Empty;

                        //Preliminary sanitizations: clean trailing space-like chars
                        nquad = nquad.Trim(new Char[] { ' ', '\t', '\r', '\n' });

                        //Skip empty or comment lines
                        if (nquad == String.Empty || nquad.StartsWith("#"))
                        {
                            continue;
                        }

                        //Tokenizes the sanitized quad
                        tokens = TokenizeNQuad(nquad);
                        #endregion

                        #region subj
                        String subj = tokens[0].TrimStart(new Char[] { '<' })
                                      .TrimEnd(new Char[] { '>' })
                                      .Replace("_:", "bnode:");
                        S = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(subj));
                        #endregion

                        #region pred
                        String pred = tokens[1].TrimStart(new Char[] { '<' })
                                      .TrimEnd(new Char[] { '>' });
                        P = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(pred));
                        #endregion

                        #region object
                        if (tokens[2].StartsWith("<") ||
                            tokens[2].StartsWith("bnode:") ||
                            tokens[2].StartsWith("_:"))
                        {
                            String obj = tokens[2].TrimStart(new Char[] { '<' })
                                         .TrimEnd(new Char[] { '>' })
                                         .Replace("_:", "bnode:")
                                         .Trim(new Char[] { ' ', '\n', '\t', '\r' });
                            O = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(obj));
                        }
                        #endregion

                        #region literal
                        else
                        {
                            #region sanitize
                            tokens[2] = RDFNTriples.regexSqt.Replace(tokens[2], String.Empty);
                            tokens[2] = RDFNTriples.regexEqt.Replace(tokens[2], String.Empty);
                            tokens[2] = tokens[2].Replace("\\\\", "\\")
                                        .Replace("\\\"", "\"")
                                        .Replace("\\n", "\n")
                                        .Replace("\\t", "\t")
                                        .Replace("\\r", "\r");
                            tokens[2] = RDFModelUtilities.ASCII_To_Unicode(tokens[2]);
                            #endregion

                            #region plain literal
                            if (!tokens[2].Contains("^^") ||
                                tokens[2].EndsWith("^^") ||
                                tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2, 1) != "<")
                            {
                                if (RDFNTriples.regexLPL.Match(tokens[2]).Success)
                                {
                                    tokens[2] = tokens[2].Replace("\"@", "@");
                                    String pLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("@", StringComparison.Ordinal));
                                    String pLitLang  = tokens[2].Substring(tokens[2].LastIndexOf("@", StringComparison.Ordinal) + 1);
                                    L = new RDFPlainLiteral(HttpUtility.HtmlDecode(pLitValue), pLitLang);
                                }
                                else
                                {
                                    L = new RDFPlainLiteral(HttpUtility.HtmlDecode(tokens[2]));
                                }
                            }
                            #endregion

                            #region typed literal
                            else
                            {
                                tokens[2] = tokens[2].Replace("\"^^", "^^");
                                String tLitValue    = tokens[2].Substring(0, tokens[2].LastIndexOf("^^", StringComparison.Ordinal));
                                String tLitDatatype = tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2)
                                                      .TrimStart(new Char[] { '<' })
                                                      .TrimEnd(new Char[] { '>' });
                                RDFModelEnums.RDFDatatypes dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
                                L = new RDFTypedLiteral(HttpUtility.HtmlDecode(tLitValue), dt);
                            }
                            #endregion
                        }
                        #endregion

                        #region context
                        if (!String.IsNullOrEmpty(tokens[3]))
                        {
                            String ctx = tokens[3].TrimStart(new Char[] { '<' })
                                         .TrimEnd(new Char[] { '>' });

                            Uri ctxUri = null;
                            if (Uri.TryCreate(ctx, UriKind.Absolute, out ctxUri))
                            {
                                C = new RDFContext(RDFModelUtilities.ASCII_To_Unicode(ctxUri.ToString()));
                            }
                            else
                            {
                                throw new RDFModelException("found context '" + ctx + "' which is not a well-formed absolute Uri");
                            }
                        }
                        #endregion

                        #region addquadruple
                        if (O != null)
                        {
                            result.AddQuadruple(new RDFQuadruple(C, S, P, O));
                        }
                        else
                        {
                            result.AddQuadruple(new RDFQuadruple(C, S, P, L));
                        }
                        #endregion
                    }
                    return(result);
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new RDFModelException("Cannot deserialize N-Quads (line " + nquadIndex + ") because: " + ex.Message, ex);
            }
        }
示例#25
0
 /// <summary>
 /// Default-ctor to build a predefined context
 /// </summary>
 public RDFContext()
 {
     this.Context         = RDFNamespaceRegister.DefaultNamespace.NamespaceUri;
     this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString());
 }
示例#26
0
 /// <summary>
 /// Gets the subgraph containing triples with the specified resource as subject
 /// </summary>
 public RDFGraph SelectTriplesBySubject(RDFResource subjectResource)
 => new RDFGraph(RDFModelUtilities.SelectTriples(this, subjectResource, null, null, null));