Esempio n. 1
0
        /// <summary>
        /// Builds a new difference store from this store and a given one
        /// </summary>
        public RDFMemoryStore DifferenceWith(RDFStore store)
        {
            RDFMemoryStore result = new RDFMemoryStore();

            if (store != null)
            {
                //Add difference quadruples
                foreach (RDFQuadruple q in this)
                {
                    if (!store.ContainsQuadruple(q))
                    {
                        result.AddQuadruple(q);
                    }
                }
            }
            else
            {
                //Add quadruples from this store
                foreach (RDFQuadruple q in this)
                {
                    result.AddQuadruple(q);
                }
            }
            return(result);
        }
Esempio n. 2
0
 /// <summary>
 /// Performs the equality comparison between two memory stores
 /// </summary>
 public bool Equals(RDFMemoryStore other)
 {
     if (other == null || this.QuadruplesCount != other.QuadruplesCount)
     {
         return(false);
     }
     foreach (RDFQuadruple q in this)
     {
         if (!other.ContainsQuadruple(q))
         {
             return(false);
         }
     }
     return(true);
 }
Esempio n. 3
0
        /// <summary>
        /// Reads a memory store by trying to dereference the given Uri
        /// </summary>
        public static RDFMemoryStore FromUri(Uri uri, int timeoutMilliseconds = 20000)
        {
            RDFMemoryStore result = new RDFMemoryStore();

            if (uri?.IsAbsoluteUri ?? false)
            {
                Uri remappedUri = RDFModelUtilities.RemapUriForDereference(uri);
                try
                {
                    HttpWebRequest webRequest = WebRequest.CreateHttp(remappedUri);
                    webRequest.MaximumAutomaticRedirections = 3;
                    webRequest.AllowAutoRedirect            = true;
                    webRequest.Timeout = timeoutMilliseconds;
                    //N-QUADS
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "application/n-quads");
                    //TRIX
                    webRequest.Headers.Add(HttpRequestHeader.Accept, "application/trix");

                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    if (webRequest.HaveResponse)
                    {
                        //N-QUADS
                        if (string.IsNullOrEmpty(webResponse.ContentType) ||
                            webResponse.ContentType.Contains("application/n-quads"))
                        {
                            result = FromStream(RDFStoreEnums.RDFFormats.NQuads, webResponse.GetResponseStream());
                        }

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

            return(result);
        }
Esempio n. 4
0
        /// <summary>
        /// Builds a new intersection store from this store and a given one
        /// </summary>
        public RDFMemoryStore IntersectWith(RDFStore store)
        {
            RDFMemoryStore result = new RDFMemoryStore();

            if (store != null)
            {
                //Add intersection quadruples
                foreach (RDFQuadruple q in this)
                {
                    if (store.ContainsQuadruple(q))
                    {
                        result.AddQuadruple(q);
                    }
                }
            }
            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// Builds the reification store of the quadruple
        /// </summary>
        public RDFStore ReifyQuadruple()
        {
            RDFStore reifStore = new RDFMemoryStore();

            reifStore.AddQuadruple(new RDFQuadruple((RDFContext)this.Context, this.ReificationSubject, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.STATEMENT));
            reifStore.AddQuadruple(new RDFQuadruple((RDFContext)this.Context, this.ReificationSubject, RDFVocabulary.RDF.SUBJECT, (RDFResource)this.Subject));
            reifStore.AddQuadruple(new RDFQuadruple((RDFContext)this.Context, this.ReificationSubject, RDFVocabulary.RDF.PREDICATE, (RDFResource)this.Predicate));
            if (this.TripleFlavor == RDFModelEnums.RDFTripleFlavor.SPO)
            {
                reifStore.AddQuadruple(new RDFQuadruple((RDFContext)this.Context, this.ReificationSubject, RDFVocabulary.RDF.OBJECT, (RDFResource)this.Object));
            }
            else
            {
                reifStore.AddQuadruple(new RDFQuadruple((RDFContext)this.Context, this.ReificationSubject, RDFVocabulary.RDF.OBJECT, (RDFLiteral)this.Object));
            }

            return(reifStore);
        }
Esempio n. 6
0
        /// <summary>
        /// Builds a new union store from this store and a given one
        /// </summary>
        public RDFMemoryStore UnionWith(RDFStore store)
        {
            RDFMemoryStore result = new RDFMemoryStore();

            //Add quadruples from this store
            foreach (RDFQuadruple q in this)
            {
                result.AddQuadruple(q);
            }

            //Manage the given store
            if (store != null)
            {
                //Add quadruples from the given store
                foreach (RDFQuadruple q in store.SelectAllQuadruples())
                {
                    result.AddQuadruple(q);
                }
            }

            return(result);
        }
Esempio n. 7
0
        /// <summary>
        /// Selects the quadruples corresponding to the given pattern from the given store
        /// </summary>
        internal static List <RDFQuadruple> SelectQuadruples(RDFMemoryStore store,
                                                             RDFContext ctx,
                                                             RDFResource subj,
                                                             RDFResource pred,
                                                             RDFResource obj,
                                                             RDFLiteral lit)
        {
            var matchCtx    = new List <RDFQuadruple>();
            var matchSubj   = new List <RDFQuadruple>();
            var matchPred   = new List <RDFQuadruple>();
            var matchObj    = new List <RDFQuadruple>();
            var matchLit    = new List <RDFQuadruple>();
            var matchResult = new List <RDFQuadruple>();

            if (store != null)
            {
                //Filter by Context
                if (ctx != null)
                {
                    foreach (var q in store.StoreIndex.SelectIndexByContext(ctx).Keys)
                    {
                        matchCtx.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Subject
                if (subj != null)
                {
                    foreach (var q in store.StoreIndex.SelectIndexBySubject(subj).Keys)
                    {
                        matchSubj.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Predicate
                if (pred != null)
                {
                    foreach (var q in store.StoreIndex.SelectIndexByPredicate(pred).Keys)
                    {
                        matchPred.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Object
                if (obj != null)
                {
                    foreach (var q in store.StoreIndex.SelectIndexByObject(obj).Keys)
                    {
                        matchObj.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Literal
                if (lit != null)
                {
                    foreach (var q in store.StoreIndex.SelectIndexByLiteral(lit).Keys)
                    {
                        matchLit.Add(store.Quadruples[q]);
                    }
                }

                //Intersect the filters
                if (ctx != null)
                {
                    if (subj != null)
                    {
                        if (pred != null)
                        {
                            if (obj != null)
                            {
                                //C->S->P->O
                                matchResult = matchCtx.Intersect(matchSubj)
                                              .Intersect(matchPred)
                                              .Intersect(matchObj)
                                              .ToList <RDFQuadruple>();
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //C->S->P->L
                                    matchResult = matchCtx.Intersect(matchSubj)
                                                  .Intersect(matchPred)
                                                  .Intersect(matchLit)
                                                  .ToList <RDFQuadruple>();
                                }
                                else
                                {
                                    //C->S->P->
                                    matchResult = matchCtx.Intersect(matchSubj)
                                                  .Intersect(matchPred)
                                                  .ToList <RDFQuadruple>();
                                }
                            }
                        }
                        else
                        {
                            if (obj != null)
                            {
                                //C->S->->O
                                matchResult = matchCtx.Intersect(matchSubj)
                                              .Intersect(matchObj)
                                              .ToList <RDFQuadruple>();
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //C->S->->L
                                    matchResult = matchCtx.Intersect(matchSubj)
                                                  .Intersect(matchLit)
                                                  .ToList <RDFQuadruple>();
                                }
                                else
                                {
                                    //C->S->->
                                    matchResult = matchCtx.Intersect(matchSubj)
                                                  .ToList <RDFQuadruple>();
                                }
                            }
                        }
                    }
                    else
                    {
                        if (pred != null)
                        {
                            if (obj != null)
                            {
                                //C->->P->O
                                matchResult = matchCtx.Intersect(matchPred)
                                              .Intersect(matchObj)
                                              .ToList <RDFQuadruple>();
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //C->->P->L
                                    matchResult = matchCtx.Intersect(matchPred)
                                                  .Intersect(matchLit)
                                                  .ToList <RDFQuadruple>();
                                }
                                else
                                {
                                    //C->->P->
                                    matchResult = matchCtx.Intersect(matchPred)
                                                  .ToList <RDFQuadruple>();
                                }
                            }
                        }
                        else
                        {
                            if (obj != null)
                            {
                                //C->->->O
                                matchResult = matchCtx.Intersect(matchObj)
                                              .ToList <RDFQuadruple>();
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //C->->->L
                                    matchResult = matchCtx.Intersect(matchLit)
                                                  .ToList <RDFQuadruple>();
                                }
                                else
                                {
                                    //C->->->
                                    matchResult = matchCtx;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (subj != null)
                    {
                        if (pred != null)
                        {
                            if (obj != null)
                            {
                                //->S->P->O
                                matchResult = matchSubj.Intersect(matchPred)
                                              .Intersect(matchObj)
                                              .ToList <RDFQuadruple>();
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //->S->P->L
                                    matchResult = matchSubj.Intersect(matchPred)
                                                  .Intersect(matchLit)
                                                  .ToList <RDFQuadruple>();
                                }
                                else
                                {
                                    //->S->P->
                                    matchResult = matchSubj.Intersect(matchPred)
                                                  .ToList <RDFQuadruple>();
                                }
                            }
                        }
                        else
                        {
                            if (obj != null)
                            {
                                //->S->->O
                                matchResult = matchSubj.Intersect(matchObj)
                                              .ToList <RDFQuadruple>();
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //->S->->L
                                    matchResult = matchSubj.Intersect(matchLit)
                                                  .ToList <RDFQuadruple>();
                                }
                                else
                                {
                                    //->S->->
                                    matchResult = matchSubj;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (pred != null)
                        {
                            if (obj != null)
                            {
                                //->->P->O
                                matchResult = matchPred.Intersect(matchObj)
                                              .ToList <RDFQuadruple>();
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //->->P->L
                                    matchResult = matchPred.Intersect(matchLit)
                                                  .ToList <RDFQuadruple>();
                                }
                                else
                                {
                                    //->->P->
                                    matchResult = matchPred;
                                }
                            }
                        }
                        else
                        {
                            if (obj != null)
                            {
                                //->->->O
                                matchResult = matchObj;
                            }
                            else
                            {
                                if (lit != null)
                                {
                                    //->->->L
                                    matchResult = matchLit;
                                }
                                else
                                {
                                    //->->->
                                    matchResult = store.Quadruples.Values.ToList <RDFQuadruple>();
                                }
                            }
                        }
                    }
                }
            }
            return(matchResult);
        }
Esempio n. 8
0
        /// <summary>
        /// Reads a memory store from a datatable with "Context-Subject-Predicate-Object" columns.
        /// </summary>
        public static RDFMemoryStore FromDataTable(DataTable table)
        {
            RDFMemoryStore result = new RDFMemoryStore();

            //Check the structure of the datatable for consistency against the "C-S-P-O" RDF model
            if (table != null && table.Columns.Count == 4)
            {
                if (table.Columns.Contains("?CONTEXT") &&
                    table.Columns.Contains("?SUBJECT") &&
                    table.Columns.Contains("?PREDICATE") &&
                    table.Columns.Contains("?OBJECT"))
                {
                    //Iterate the rows of the datatable
                    foreach (DataRow tableRow in table.Rows)
                    {
                        #region CONTEXT
                        //Parse the quadruple context
                        if (!tableRow.IsNull("?CONTEXT") && !string.IsNullOrEmpty(tableRow["?CONTEXT"].ToString()))
                        {
                            var rowCont = RDFQueryUtilities.ParseRDFPatternMember(tableRow["?CONTEXT"].ToString());
                            if (rowCont is RDFResource && !((RDFResource)rowCont).IsBlank)
                            {
                                #region SUBJECT
                                //Parse the quadruple subject
                                if (!tableRow.IsNull("?SUBJECT") && !string.IsNullOrEmpty(tableRow["?SUBJECT"].ToString()))
                                {
                                    var rowSubj = RDFQueryUtilities.ParseRDFPatternMember(tableRow["?SUBJECT"].ToString());
                                    if (rowSubj is RDFResource)
                                    {
                                        #region PREDICATE
                                        //Parse the quadruple predicate
                                        if (!tableRow.IsNull("?PREDICATE") && !string.IsNullOrEmpty(tableRow["?PREDICATE"].ToString()))
                                        {
                                            var rowPred = RDFQueryUtilities.ParseRDFPatternMember(tableRow["?PREDICATE"].ToString());
                                            if (rowPred is RDFResource && !((RDFResource)rowPred).IsBlank)
                                            {
                                                #region OBJECT
                                                //Parse the quadruple object
                                                if (!tableRow.IsNull("?OBJECT"))
                                                {
                                                    var rowObj = RDFQueryUtilities.ParseRDFPatternMember(tableRow["?OBJECT"].ToString());
                                                    if (rowObj is RDFResource)
                                                    {
                                                        result.AddQuadruple(new RDFQuadruple(new RDFContext(rowCont.ToString()), (RDFResource)rowSubj, (RDFResource)rowPred, (RDFResource)rowObj));
                                                    }
                                                    else
                                                    {
                                                        result.AddQuadruple(new RDFQuadruple(new RDFContext(rowCont.ToString()), (RDFResource)rowSubj, (RDFResource)rowPred, (RDFLiteral)rowObj));
                                                    }
                                                }
                                                else
                                                {
                                                    throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter contains a row having NULL value in the \"?OBJECT\" column.");
                                                }
                                                #endregion
                                            }
                                            else
                                            {
                                                throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter contains a row having a blank resource or a literal in the \"?PREDICATE\" column.");
                                            }
                                        }
                                        else
                                        {
                                            throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter contains a row having NULL or empty value in the \"?PREDICATE\" column.");
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter contains a row not having a resource in the \"?SUBJECT\" column.");
                                    }
                                }
                                else
                                {
                                    throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter contains a row having NULL or empty value in the \"?SUBJECT\" column.");
                                }
                                #endregion
                            }
                            else
                            {
                                throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter contains a row having a blank resource or a literal in the \"?CONTEXT\" column.");
                            }
                        }
                        else
                        {
                            throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter contains a row having NULL or empty value in the \"?CONTEXT\" column.");
                        }
                        #endregion
                    }
                }
                else
                {
                    throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter does not have the required columns \"?CONTEXT\", \"?SUBJECT\", \"?PREDICATE\", \"?OBJECT\".");
                }
            }
            else
            {
                throw new RDFStoreException("Cannot read RDF memory store from datatable because given \"table\" parameter is null, or it does not have exactly 4 columns.");
            }

            return(result);
        }
Esempio n. 9
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)) {
                    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("\\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.RDFDatatype 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);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Deserializes the given TriX stream to a memory store.
        /// </summary>
        internal static RDFMemoryStore Deserialize(Stream inputStream)
        {
            try
            {
                #region deserialize
                RDFMemoryStore result = new RDFMemoryStore();
                Dictionary <Int64, RDFGraph> graphs = new Dictionary <Int64, RDFGraph>();
                using (StreamReader streamReader = new StreamReader(inputStream, Encoding.UTF8))
                {
                    using (XmlTextReader trixReader = new XmlTextReader(streamReader))
                    {
                        trixReader.DtdProcessing = DtdProcessing.Parse;
                        trixReader.Normalization = false;

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

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

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

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

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

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

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

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

                                        #region literal

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

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

                                        #endregion

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

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

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

                #endregion
            }
            catch (Exception ex)
            {
                throw new RDFModelException("Cannot deserialize TriX because: " + ex.Message, ex);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Selects the quadruples corresponding to the given pattern from the given store
        /// </summary>
        internal static List <RDFQuadruple> SelectQuadruples(RDFMemoryStore store, RDFContext ctx, RDFResource subj, RDFResource pred, RDFResource obj, RDFLiteral lit)
        {
            List <RDFQuadruple> matchResult = new List <RDFQuadruple>();

            if (store != null)
            {
                List <RDFQuadruple> C            = new List <RDFQuadruple>();
                List <RDFQuadruple> S            = new List <RDFQuadruple>();
                List <RDFQuadruple> P            = new List <RDFQuadruple>();
                List <RDFQuadruple> O            = new List <RDFQuadruple>();
                List <RDFQuadruple> L            = new List <RDFQuadruple>();
                StringBuilder       queryFilters = new StringBuilder();

                //Filter by Context
                if (ctx != null)
                {
                    queryFilters.Append("C");
                    foreach (long q in store.StoreIndex.SelectIndexByContext(ctx))
                    {
                        C.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Subject
                if (subj != null)
                {
                    queryFilters.Append("S");
                    foreach (long q in store.StoreIndex.SelectIndexBySubject(subj))
                    {
                        S.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Predicate
                if (pred != null)
                {
                    queryFilters.Append("P");
                    foreach (long q in store.StoreIndex.SelectIndexByPredicate(pred))
                    {
                        P.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Object
                if (obj != null)
                {
                    queryFilters.Append("O");
                    foreach (long q in store.StoreIndex.SelectIndexByObject(obj))
                    {
                        O.Add(store.Quadruples[q]);
                    }
                }

                //Filter by Literal
                if (lit != null)
                {
                    queryFilters.Append("L");
                    foreach (var q in store.StoreIndex.SelectIndexByLiteral(lit))
                    {
                        L.Add(store.Quadruples[q]);
                    }
                }

                //Intersect the filters
                string queryFilter = queryFilters.ToString();
                switch (queryFilter)
                {
                case "C":
                    matchResult = C;
                    break;

                case "S":
                    matchResult = S;
                    break;

                case "P":
                    matchResult = P;
                    break;

                case "O":
                    matchResult = O;
                    break;

                case "L":
                    matchResult = L;
                    break;

                case "CS":
                    matchResult = C.Intersect(S).ToList();
                    break;

                case "CP":
                    matchResult = C.Intersect(P).ToList();
                    break;

                case "CO":
                    matchResult = C.Intersect(O).ToList();
                    break;

                case "CL":
                    matchResult = C.Intersect(L).ToList();
                    break;

                case "CSP":
                    matchResult = C.Intersect(S).Intersect(P).ToList();
                    break;

                case "CSO":
                    matchResult = C.Intersect(S).Intersect(O).ToList();
                    break;

                case "CSL":
                    matchResult = C.Intersect(S).Intersect(L).ToList();
                    break;

                case "CPO":
                    matchResult = C.Intersect(P).Intersect(O).ToList();
                    break;

                case "CPL":
                    matchResult = C.Intersect(P).Intersect(L).ToList();
                    break;

                case "CSPO":
                    matchResult = C.Intersect(S).Intersect(P).Intersect(O).ToList();
                    break;

                case "CSPL":
                    matchResult = C.Intersect(S).Intersect(P).Intersect(L).ToList();
                    break;

                case "SP":
                    matchResult = S.Intersect(P).ToList();
                    break;

                case "SO":
                    matchResult = S.Intersect(O).ToList();
                    break;

                case "SL":
                    matchResult = S.Intersect(L).ToList();
                    break;

                case "SPO":
                    matchResult = S.Intersect(P).Intersect(O).ToList();
                    break;

                case "SPL":
                    matchResult = S.Intersect(P).Intersect(L).ToList();
                    break;

                case "PO":
                    matchResult = P.Intersect(O).ToList();
                    break;

                case "PL":
                    matchResult = P.Intersect(L).ToList();
                    break;

                default:
                    matchResult = store.ToList();
                    break;
                }
            }
            return(matchResult);
        }