コード例 #1
0
 /// <summary>
 /// Rebuild the metadata of the given graph
 /// </summary>
 internal static void RebuildGraph(RDFGraph graph) {
     var triples = new Dictionary<Int64, RDFTriple>(graph.Triples);
     graph.ClearTriples();
     foreach (var t in triples) {
         graph.AddTriple(t.Value);
     }
 }
コード例 #2
0
 /// <summary>
 /// Writes the given graph to the given file in the given RDF syntax. 
 /// </summary>
 public static void WriteRDF(RDFModelEnums.RDFSyntaxes rdfSyntax, RDFGraph graph, String filepath) {
     if (graph != null) {
         if (filepath != null && filepath.Trim() != String.Empty) {
             switch(rdfSyntax) {
                 case RDFModelEnums.RDFSyntaxes.NTriples:
                     RDFNTriples.Serialize(graph, filepath);
                     break;
                 case RDFModelEnums.RDFSyntaxes.RdfXml:
                     RDFXml.Serialize(graph, filepath);
                     break;
                 case RDFModelEnums.RDFSyntaxes.TriX:
                     RDFTrix.Serialize(graph, filepath);
                     break;
                 case RDFModelEnums.RDFSyntaxes.Turtle:
                     RDFTurtle.Serialize(graph, filepath);
                     break;
                 default:
                     throw new RDFModelException("Cannot write RDF file because " + rdfSyntax + " writing is not supported.");
             }
         }
         else {
             throw new RDFModelException("Cannot write RDF file because given \"filepath\" parameter is null or empty.");
         }
     }
     else {
         throw new RDFModelException("Cannot write RDF file because given \"graph\" parameter is null.");
     }
 }
コード例 #3
0
 /// <summary>
 /// Writes the given graph to the given file in the given RDF format. 
 /// </summary>
 public static void WriteRDF(RDFModelEnums.RDFFormats rdfFormat, RDFGraph graph, String filepath) {
     if (graph        != null) {
         if (filepath != null) {
             switch(rdfFormat) {
                 case RDFModelEnums.RDFFormats.NTriples:
                      RDFNTriples.Serialize(graph, filepath);
                      break;
                 case RDFModelEnums.RDFFormats.RdfXml:
                      RDFXml.Serialize(graph, filepath);
                      break;
                 case RDFModelEnums.RDFFormats.TriX:
                      RDFTrix.Serialize(graph, filepath);
                      break;
                 case RDFModelEnums.RDFFormats.Turtle:
                      RDFTurtle.Serialize(graph, filepath);
                      break;
             }
         }
         else {
             throw new RDFModelException("Cannot write RDF file because given \"filepath\" parameter is null.");
         }
     }
     else {
         throw new RDFModelException("Cannot write RDF file because given \"graph\" parameter is null.");
     }
 }
コード例 #4
0
        /// <summary>
        /// Builds a query result corresponding to the given graph
        /// </summary>
        public static RDFDescribeQueryResult FromRDFGraph(RDFGraph graph) {
            RDFDescribeQueryResult result = new RDFDescribeQueryResult(String.Empty);
            if (graph != null) {

                //Transform the graph into a datatable and assign it to the query result
                result.DescribeResults    = graph.ToDataTable();

            }
            return result;
        }
コード例 #5
0
        protected override void BuildRDFGraph()
        {
            RDFGraph.Assert(new Triple(un, RDF_TYPE, LDP_RDF_RESOURCE));
            RDFGraph.Assert(new Triple(un, DCT_IDENTIFIER, RDFGraph.CreateLiteralNode(attribute.Prototype.Name, "xsd:string")));

            string compUri = dp_uri.Replace("/" + attribute.Prototype.Name, "");

            RDFGraph.Assert(new Triple(un, DCT_IS_PART_OF, RDFGraph.CreateUriNode(new Uri(compUri))));
            string valuestring = attribute?.Value?.ToString() ?? "null";

            RDFGraph.Assert(new Triple(un, RDF_VALUE, RDFGraph.CreateLiteralNode(valuestring, attribute.Type.transformTypeToString())));
        }
コード例 #6
0
        private void BuildGraph(RDFGraph graph, int count)
        {
            RDFResource tempObject1 = new RDFResource(string.Concat(RDF.BASE_URI, "example_object_1"));
            RDFResource tempObject2 = new RDFResource(string.Concat(RDF.BASE_URI, "example_object_2"));

            for (int i = 0; i < count; i++)
            {
                RDFResource newSubject = new RDFResource(string.Concat(RDF.BASE_URI, "example_subject_" + i));
                RDFResource newObject  = (count < 30) ? tempObject1 : tempObject2;
                graph.AddTriple(new RDFTriple(newSubject, RDF.TYPE, newObject));
            }
        }
コード例 #7
0
        public void Load()
        {
            //RDFOntology ont = RDFSKOSOntology.Instance;

            //ont.Data.From

            //var graph = ont.Data.ToRDFGraph(RDFSemanticsEnums.RDFOntologyInferenceExportBehavior.ModelAndData);
            //RDFGraph graph = RDFGraph.FromFile(RDFModelEnums.RDFFormats.Turtle, @"C:\Users\philippel\Documents\ONU\unescothes.ttl");
            RDFGraph graph = RDFGraph.FromFile(RDFModelEnums.RDFFormats.RdfXml, @"C:\Users\philippel\Documents\ONU\unescothes.rdf");

            long triplesCount = graph.TriplesCount;
        }
コード例 #8
0
        public RDFSharpBenchmark()
        {
            this.monaLisa        = new RDFResource("http://www.wikidata.org/entity/Q12418");
            this.creator         = new RDFResource("http://purl.org/dc/terms/creator");
            this.title           = new RDFResource("http://purl.org/dc/terms/title");
            this.leonardoDaVinci = new RDFResource("http://dbpedia.org/resource/Leonardo_da_Vinci");
            FileStream fs = File.OpenRead(@"../../../../../../..//TestData/szepmuveszeti.n3");

            this.museumGraph     = RDFGraph.FromStream(RDFModelEnums.RDFFormats.Turtle, fs);
            this.monaLisaCreator = new RDFTriple(this.monaLisa, this.creator, this.leonardoDaVinci);
            this.monaLisaTitle   = new RDFPlainLiteral("Mona Lisa");
        }
コード例 #9
0
ファイル: RDFTargetClass.cs プロジェクト: dgerding/RDFSharp
        /// <summary>
        /// Gets a graph representation of this target
        /// </summary>
        internal override RDFGraph ToRDFGraph(RDFShape shape)
        {
            var result = new RDFGraph();

            //sh:targetClass
            if (shape != null)
            {
                result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.TARGET_CLASS, this.TargetValue));
            }

            return(result);
        }
コード例 #10
0
        /// <summary>
        /// Gets a graph representation of this target
        /// </summary>
        internal override RDFGraph ToRDFGraph(RDFShape shape)
        {
            var result = new RDFGraph();

            //sh:targetSubjectsOf
            if (shape != null)
            {
                result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.TARGET_SUBJECTS_OF, this.TargetValue));
            }

            return(result);
        }
コード例 #11
0
        public void TestTurtleSerialization()
        {
            // Arrange
            graph = new RDFGraph();
            BuildGraph(graph, 50);

            // Act
            SerializeGraph(graph, RDFModelEnums.RDFFormats.Turtle);
            RDFGraph newGraph = DeserializateGraph(RDFModelEnums.RDFFormats.Turtle);

            // Assert
            Assert.AreEqual(graph.TriplesCount, newGraph.TriplesCount);
        }
コード例 #12
0
        protected override void BuildRDFGraph()
        {
            RDFGraph.Assert(new Triple(un, RDF_TYPE, LDP_BASIC_CONTAINER));
            RDFGraph.Assert(new Triple(un, DCT_IDENTIFIER, n_c));
            RDFGraph.Assert(new Triple(un, DCT_IS_PART_OF, GetContainingEntityURI()));
            RDFGraph.Assert(new Triple(un, LDP_HASMEMBERRELATION, DCT_HAS_PART));

            var definedByUri = new Uri(u.getPrototypeBaseUri() + c.Name + "/");

            RDFGraph.Assert(new Triple(un, RDFS_IS_DEFINED_BY, RDFGraph.CreateUriNode(definedByUri)));

            CreateAttributeTriples();
        }
コード例 #13
0
        public static void CreatingSimpleGraphTest()
        {
            RDFGraph waltdisney = GraphBuilder.WaltDisneyGraphBuild();
            var      graphEnum  = waltdisney.TriplesEnumerator;

            graphEnum.MoveNext();
            Assert.Equal("http://www.waltdisney.com/mickey_mouse", graphEnum.Current.Subject.ToString());
            Assert.Equal("http://xmlns.com/foaf/0.1/age", graphEnum.Current.Predicate.ToString());
            Assert.Equal("85^^http://www.w3.org/2001/XMLSchema#integer", graphEnum.Current.Object.ToString());
            graphEnum.MoveNext();
            Assert.Equal("http://www.waltdisney.com/donald_duck", graphEnum.Current.Subject.ToString());
            Assert.Equal("http://xmlns.com/foaf/0.1/name", graphEnum.Current.Predicate.ToString());
            Assert.Equal("Donald Duck", graphEnum.Current.Object.ToString());
        }
コード例 #14
0
        /// <summary>
        /// Applies the query to the given graph
        /// </summary>
        public RDFDescribeQueryResult ApplyToGraph(RDFGraph graph)
        {
            if (graph != null)
            {
                this.PatternGroupResultTables.Clear();
                this.PatternResultTables.Clear();

                RDFDescribeQueryResult describeResult = new RDFDescribeQueryResult(this.ToString());
                if (!this.IsEmpty)
                {
                    //Iterate the pattern groups of the query
                    foreach (RDFPatternGroup patternGroup in this.PatternGroups)
                    {
                        //Step 1: Get the intermediate result tables of the current pattern group
                        RDFDescribeQueryEngine.EvaluatePatterns(this, patternGroup, graph);

                        //Step 2: Get the result table of the current pattern group
                        RDFDescribeQueryEngine.CombinePatterns(this, patternGroup);

                        //Step 3: Apply the filters of the current pattern group to its result table
                        RDFDescribeQueryEngine.ApplyFilters(this, patternGroup);
                    }

                    //Step 4: Get the result table of the query
                    DataTable queryResultTable = RDFQueryEngine.CombineTables(this.PatternGroupResultTables.Values.ToList <DataTable>(), false);

                    //Step 5: Describe the terms from the result table
                    DataTable describeResultTable = RDFDescribeQueryEngine.DescribeTerms(this, graph, queryResultTable);

                    //Step 6: Apply the modifiers of the query to the result table
                    describeResult.DescribeResults = RDFDescribeQueryEngine.ApplyModifiers(this, describeResultTable);
                }
                else
                {
                    //In this case the only chance to proceed is to have resources in the describe terms,
                    //which will be used to search for S-P-O data. Variables are omitted in this scenario.
                    if (this.DescribeTerms.Any(dt => dt is RDFResource))
                    {
                        //Step 1: Describe the terms from the result table
                        DataTable describeResultTable = RDFDescribeQueryEngine.DescribeTerms(this, graph, new DataTable());

                        //Step 2: Apply the modifiers of the query to the result table
                        describeResult.DescribeResults = RDFDescribeQueryEngine.ApplyModifiers(this, describeResultTable);
                    }
                }

                return(describeResult);
            }
            throw new RDFQueryException("Cannot execute DESCRIBE query because given \"graph\" parameter is null.");
        }
コード例 #15
0
        /// <summary>
        /// Applies the query to the given SPARQL endpoint
        /// </summary>
        public RDFDescribeQueryResult ApplyToSPARQLEndpoint(RDFSPARQLEndpoint sparqlEndpoint)
        {
            RDFDescribeQueryResult describeResult = new RDFDescribeQueryResult(this.ToString());

            if (sparqlEndpoint != null)
            {
                RDFQueryEvents.RaiseDESCRIBEQueryEvaluation(String.Format("Evaluating DESCRIBE query on SPARQL endpoint '{0}'...", sparqlEndpoint));

                //Establish a connection to the given SPARQL endpoint
                using (WebClient webClient = new WebClient())
                {
                    //Insert reserved "query" parameter
                    webClient.QueryString.Add("query", HttpUtility.UrlEncode(this.ToString()));

                    //Insert user-provided parameters
                    webClient.QueryString.Add(sparqlEndpoint.QueryParams);

                    //Insert request headers
                    webClient.Headers.Add(HttpRequestHeader.Accept, "application/turtle");
                    webClient.Headers.Add(HttpRequestHeader.Accept, "text/turtle");

                    //Send querystring to SPARQL endpoint
                    var sparqlResponse = webClient.DownloadData(sparqlEndpoint.BaseAddress);

                    //Parse response from SPARQL endpoint
                    if (sparqlResponse != null)
                    {
                        using (var sStream = new MemoryStream(sparqlResponse))
                        {
                            describeResult = RDFDescribeQueryResult.FromRDFGraph(RDFGraph.FromStream(RDFModelEnums.RDFFormats.Turtle, sStream));
                        }
                        describeResult.DescribeResults.TableName = this.ToString();
                    }
                }

                //Eventually adjust column names (should start with "?")
                Int32 columnsCount = describeResult.DescribeResults.Columns.Count;
                for (Int32 i = 0; i < columnsCount; i++)
                {
                    if (!describeResult.DescribeResults.Columns[i].ColumnName.StartsWith("?"))
                    {
                        describeResult.DescribeResults.Columns[i].ColumnName = "?" + describeResult.DescribeResults.Columns[i].ColumnName;
                    }
                }

                RDFQueryEvents.RaiseDESCRIBEQueryEvaluation(String.Format("Evaluated DESCRIBE query on SPARQL endpoint '{0}': Found '{1}' results.", sparqlEndpoint, describeResult.DescribeResultsCount));
            }
            return(describeResult);
        }
コード例 #16
0
 public ComponentPrototypeGraph(Uri u, ReadOnlyComponentPrototype p) : base(u)
 {
     componentPrototype = p;
     RDFGraph.NamespaceMap.AddNamespace("eca", new Uri("http://www.dfki.de/eca#"));
     ECA_COMPONENT   = RDFGraph.CreateUriNode("eca:component");
     attributesGraph = new Graph();
     attributesGraph.NamespaceMap.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
     attributesGraph.NamespaceMap.AddNamespace("ldp", new Uri("http://www.w3.org/ns/ldp#"));
     attributesGraph.NamespaceMap.AddNamespace("dct", new Uri("http://purl.org/dc/terms/"));
     attributesGraph.NamespaceMap.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#"));
     attributesGraph.NamespaceMap.AddNamespace("eca", new Uri("http://www.dfki.de/eca#"));
     createAttributePrototypesGraph();
     BuildRDFGraph();
     RDFGraph.Merge(attributesGraph, false);
 }
コード例 #17
0
        private void BuildGraph(RDFGraph graph)
        {
            const int OBJ_COUNT  = 3;
            const int SUBJ_COUNT = 10;

            for (int i = 0; i < OBJ_COUNT; i++)
            {
                RDFResource obj = new RDFResource(string.Concat(RDF.BASE_URI, "example_object" + i));
                for (int j = 0; j < SUBJ_COUNT; j++)
                {
                    RDFResource tempSubject = new RDFResource(string.Concat(RDF.BASE_URI, "example_subject" + j));
                    graph.AddTriple(new RDFTriple(tempSubject, RDF.TYPE, obj));
                }
            }
        }
コード例 #18
0
        public void RemoveTripleByPredicateTest()
        {
            var testGraph = new RDFGraph(defaultTriples);
            var old       = new List <RDFTriple>(defaultTriples);

            old.Remove(defaultTriples[0]);
            testGraph.RemoveTriplesByPredicate(TestModelObject.predRes[0]);
            var newList = new List <RDFTriple>();

            foreach (var triple in testGraph)
            {
                newList.Add(triple);
            }

            Assert.Equal(old, newList);
        }
コード例 #19
0
        public void TestSelectAll()
        {
            // Arrange
            graph = new RDFGraph();
            RDFSelectQuery query;

            BuildGraph(graph);

            // Act
            query = BuildSelectAllQuery();
            var result = query.ApplyToGraph(graph);

            Console.WriteLine(query.ToString());

            // Assert
            Assert.AreEqual(30, result.SelectResultsCount);
        }
コード例 #20
0
        public Graph getMergedGraph()
        {
            Graph mergedGraph = RDFGraph.CopyGraph();

            mergedGraph.Assert(new Triple(un, RDF_VALUE, RDFGraph.CreateLiteralNode(attribute.Value.ToString(), new Uri("xsd:attributeValue"))));
            if (attribute.Type.Equals(typeof(EntityCollection)))
            {
                foreach (Entity e in (EntityCollection)attribute.Value)
                {
                    mergedGraph.Assert(new Triple(un,
                                                  RDFGraph.CreateUriNode("ldp:contains"),
                                                  RDFGraph.CreateUriNode(new Uri(e.GetDatapoint().Route))
                                                  ));
                }
            }
            return(mergedGraph);
        }
コード例 #21
0
        public void TestSelectLimitModifier()
        {
            // Arrange
            graph = new RDFGraph();
            RDFSelectQuery query;

            BuildGraph(graph);

            // Act
            query = BuildSelectAllQuery();
            query.AddModifier(new RDFLimitModifier(5));

            var result = query.ApplyToGraph(graph);

            // Assert
            Assert.AreEqual(5, result.SelectResultsCount);
        }
コード例 #22
0
        public void SelectTriplesBySubjectTest()
        {
            var testGraph = new RDFGraph(defaultTriples);
            var old       = new List <RDFTriple>()
            {
                defaultTriples[0]
            };
            var res     = testGraph.SelectTriplesBySubject(TestModelObject.subRes[0]);
            var newList = new List <RDFTriple>();

            foreach (var triple in res)
            {
                newList.Add(triple);
            }

            Assert.Equal(old, newList);
        }
コード例 #23
0
        public void AddTripleTest()
        {
            var testGraph = new RDFGraph(defaultTriples);
            var old       = new List <RDFTriple>(defaultTriples);
            var newTriple = TestModelObject.triples[2];

            old.Add(newTriple);
            testGraph.AddTriple(newTriple);
            var newList = new List <RDFTriple>();

            foreach (var triple in testGraph)
            {
                newList.Add(triple);
            }

            Assert.Equal(old, newList);
        }
コード例 #24
0
        /// <summary>
        /// Applies the query to the given SPARQL endpoint
        /// </summary>
        public RDFConstructQueryResult ApplyToSPARQLEndpoint(RDFSPARQLEndpoint sparqlEndpoint)
        {
            RDFConstructQueryResult constructResult = new RDFConstructQueryResult(this.ToString());

            if (sparqlEndpoint != null)
            {
                //Establish a connection to the given SPARQL endpoint
                using (WebClient webClient = new WebClient())
                {
                    //Insert reserved "query" parameter
                    webClient.QueryString.Add("query", HttpUtility.UrlEncode(this.ToString()));

                    //Insert user-provided parameters
                    webClient.QueryString.Add(sparqlEndpoint.QueryParams);

                    //Insert request headers
                    webClient.Headers.Add(HttpRequestHeader.Accept, "application/turtle");
                    webClient.Headers.Add(HttpRequestHeader.Accept, "text/turtle");

                    //Send querystring to SPARQL endpoint
                    byte[] sparqlResponse = webClient.DownloadData(sparqlEndpoint.BaseAddress);

                    //Parse response from SPARQL endpoint
                    if (sparqlResponse != null)
                    {
                        using (var sStream = new MemoryStream(sparqlResponse))
                        {
                            constructResult = RDFConstructQueryResult.FromRDFGraph(RDFGraph.FromStream(RDFModelEnums.RDFFormats.Turtle, sStream));
                        }
                        constructResult.ConstructResults.TableName = this.ToString();
                    }
                }

                //Eventually adjust column names (should start with "?")
                int columnsCount = constructResult.ConstructResults.Columns.Count;
                for (int i = 0; i < columnsCount; i++)
                {
                    if (!constructResult.ConstructResults.Columns[i].ColumnName.StartsWith("?"))
                    {
                        constructResult.ConstructResults.Columns[i].ColumnName = string.Concat("?", constructResult.ConstructResults.Columns[i].ColumnName);
                    }
                }
            }
            return(constructResult);
        }
コード例 #25
0
 /// <summary>
 /// Merges the given graph into the store, avoiding duplicate insertions
 /// </summary>
 public override RDFStore MergeGraph(RDFGraph graph)
 {
     if (graph != null)
     {
         RDFContext graphCtx = new RDFContext(graph.Context);
         foreach (RDFTriple t in graph)
         {
             if (t.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO)
             {
                 this.AddQuadruple(new RDFQuadruple(graphCtx, (RDFResource)t.Subject, (RDFResource)t.Predicate, (RDFResource)t.Object));
             }
             else
             {
                 this.AddQuadruple(new RDFQuadruple(graphCtx, (RDFResource)t.Subject, (RDFResource)t.Predicate, (RDFLiteral)t.Object));
             }
         }
     }
     return(this);
 }
コード例 #26
0
        /// <summary>
        /// Gets a graph representation of this ontology data, exporting inferences according to the selected behavior
        /// </summary>
        public RDFGraph ToRDFGraph(RDFSemanticsEnums.RDFOntologyInferenceExportBehavior infexpBehavior)
        {
            var result = new RDFGraph();

            //Relations
            result = result.UnionWith(this.Relations.SameAs.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Relations.DifferentFrom.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Relations.ClassType.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Relations.Assertions.ToRDFGraph(infexpBehavior));

            //Annotations
            result = result.UnionWith(this.Annotations.VersionInfo.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Annotations.Comment.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Annotations.Label.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Annotations.SeeAlso.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Annotations.IsDefinedBy.ToRDFGraph(infexpBehavior))
                     .UnionWith(this.Annotations.CustomAnnotations.ToRDFGraph(infexpBehavior));

            return(result);
        }
コード例 #27
0
        private void BuildGraphWithValues(RDFGraph grap)
        {
            const int SUBJ_COUNT = 5;
            const int VAL_COUNT  = 5;

            RDFResource obj = new RDFResource(string.Concat(RDF.BASE_URI, "example_object"));

            for (int j = 0; j < SUBJ_COUNT; j++)
            {
                RDFResource tempSubject = new RDFResource(string.Concat(RDF.BASE_URI, "example_subject" + j));
                graph.AddTriple(new RDFTriple(tempSubject, RDF.TYPE, obj));
                for (int k = 0; k < VAL_COUNT; k++)
                {
                    int tempValue = (j + 1) * 10;
                    graph.AddTriple(new RDFTriple(
                                        tempSubject,
                                        RDF.VALUE,
                                        new RDFTypedLiteral(tempValue.ToString(), RDFModelEnums.RDFDatatypes.XSD_INTEGER)));
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Builds a graph corresponding to the query result
        /// </summary>
        public RDFGraph ToRDFGraph() {
            RDFGraph result        = new RDFGraph();
            RDFPatternMember subj  = null;
            RDFPatternMember pred  = null;
            RDFPatternMember obj   = null;

            //Iterate the datatable rows and generate the corresponding triples to be added to the result graph
            IEnumerator resultRows = this.DescribeResults.Rows.GetEnumerator();
            while (resultRows.MoveNext()) {
                subj               = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["SUBJECT"].ToString());
                pred               = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["PREDICATE"].ToString());
                obj                = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["OBJECT"].ToString());
                if (obj is RDFResource) {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFResource)obj));
                }
                else {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFLiteral)obj));
                }
            }

            return result;
        }
コード例 #29
0
        public static RDFGraph WaltDisneyGraphBuild()
        {
            RDFResource donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck");

            RDFPlainLiteral donaldduck_name = new RDFPlainLiteral("Donald Duck");
            //create typed literal
            // "85"^^xsd:integer
            RDFTypedLiteral mickeymouse_age = new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER);
            RDFTypedLiteral donaldduck_age  = new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER);


            //create triples
            // "Mickey Mouse is 85 years old"
            RDFTriple mickeymouse_is85yr = new RDFTriple(new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                                                         RDFVocabulary.FOAF.AGE,
                                                         mickeymouse_age);

            // "Donald Duck has English-US name "Donald Duck""
            RDFTriple donaldduck_name_enus_triple = new RDFTriple(donaldduck,
                                                                  RDFVocabulary.FOAF.NAME,
                                                                  donaldduck_name);

            // "Donald Duck is 85 years old"
            RDFTriple donaldduck_is85yr = new RDFTriple(donaldduck,
                                                        RDFVocabulary.FOAF.AGE,
                                                        donaldduck_age);



            List <RDFTriple> triples = new List <RDFTriple> {
                mickeymouse_is85yr, donaldduck_name_enus_triple, donaldduck_is85yr
            };

            RDFGraph waltdisney = new RDFGraph(triples);

            waltdisney.SetContext(new Uri("http://waltdisney.com/"));

            return(waltdisney);
        }
コード例 #30
0
        /// <summary>
        /// Applies the query to the given SPARQL endpoint
        /// </summary>
        public RDFConstructQueryResult ApplyToSPARQLEndpoint(RDFSPARQLEndpoint sparqlEndpoint)
        {
            RDFConstructQueryResult constructResult = new RDFConstructQueryResult(this.ToString());

            if (sparqlEndpoint != null)
            {
                RDFQueryEvents.RaiseCONSTRUCTQueryEvaluation(String.Format("Evaluating CONSTRUCT query on SPARQL endpoint '{0}'...", sparqlEndpoint));

                //Establish a connection to the given SPARQL endpoint
                using (WebClient webClient = new WebClient())
                {
                    //Insert reserved "query" parameter
                    webClient.QueryString.Add("query", HttpUtility.UrlEncode(this.ToString()));

                    //Insert user-provided parameters
                    webClient.QueryString.Add(sparqlEndpoint.QueryParams);

                    //Insert request headers
                    webClient.Headers.Add(HttpRequestHeader.Accept, "application/turtle");
                    webClient.Headers.Add(HttpRequestHeader.Accept, "text/turtle");

                    //Send querystring to SPARQL endpoint
                    var sparqlResponse = webClient.DownloadData(sparqlEndpoint.BaseAddress);

                    //Parse response from SPARQL endpoint
                    if (sparqlResponse != null)
                    {
                        using (var sStream = new MemoryStream(sparqlResponse))
                        {
                            constructResult = RDFConstructQueryResult.FromRDFGraph(RDFGraph.FromStream(RDFModelEnums.RDFFormats.Turtle, sStream));
                        }
                        constructResult.ConstructResults.TableName = this.ToString();
                    }
                }

                RDFQueryEvents.RaiseCONSTRUCTQueryEvaluation(String.Format("Evaluated CONSTRUCT query on SPARQL endpoint '{0}': Found '{1}' results.", sparqlEndpoint, constructResult.ConstructResultsCount));
            }
            return(constructResult);
        }
コード例 #31
0
        public void TestSelectDistinctModifier()
        {
            // Arrange
            graph = new RDFGraph();
            RDFSelectQuery query;

            BuildGraph(graph);
            graph.AddTriple(        // add duplicate triple
                new RDFTriple(
                    new RDFResource(string.Concat(RDF.BASE_URI, "example_subject" + 0)),
                    RDF.TYPE,
                    new RDFResource(string.Concat(RDF.BASE_URI, "example_object" + 0))
                    )
                );

            // Act
            query = BuildSelectAllQuery();
            query.AddModifier(new RDFDistinctModifier());
            var result = query.ApplyToGraph(graph);

            // Assert
            Assert.AreEqual(30, result.SelectResultsCount);
        }
コード例 #32
0
        /// <summary>
        /// Applies the query to the given graph
        /// </summary>
        public RDFConstructQueryResult ApplyToGraph(RDFGraph graph)
        {
            if (graph != null)
            {
                this.PatternGroupResultTables.Clear();
                this.PatternResultTables.Clear();

                RDFConstructQueryResult constructResult = new RDFConstructQueryResult(this.ToString());
                if (!this.IsEmpty)
                {
                    //Iterate the pattern groups of the query
                    foreach (RDFPatternGroup patternGroup in this.PatternGroups)
                    {
                        //Step 1: Get the intermediate result tables of the current pattern group
                        RDFConstructQueryEngine.EvaluatePatterns(this, patternGroup, graph);

                        //Step 2: Get the result table of the current pattern group
                        RDFConstructQueryEngine.CombinePatterns(this, patternGroup);

                        //Step 3: Apply the filters of the current pattern group to its result table
                        RDFConstructQueryEngine.ApplyFilters(this, patternGroup);
                    }

                    //Step 4: Get the result table of the query
                    DataTable queryResultTable = RDFQueryEngine.CombineTables(this.PatternGroupResultTables.Values.ToList <DataTable>(), false);

                    //Step 5: Fill the templates from the result table
                    DataTable filledResultTable = RDFConstructQueryEngine.FillTemplates(this, queryResultTable);

                    //Step 6: Apply the modifiers of the query to the result table
                    constructResult.ConstructResults = RDFConstructQueryEngine.ApplyModifiers(this, filledResultTable);
                }

                return(constructResult);
            }
            throw new RDFQueryException("Cannot execute CONSTRUCT query because given \"graph\" parameter is null.");
        }
コード例 #33
0
        private void SerializeGraph(RDFGraph graph, RDFModelEnums.RDFFormats format)
        {
            // create file path
            DirectoryInfo di = Directory.CreateDirectory("graphs");

            switch (format)
            {
            case RDFModelEnums.RDFFormats.NTriples:
                graph.ToFile(RDFModelEnums.RDFFormats.NTriples, "graphs/NTriples.txt");
                break;

            case RDFModelEnums.RDFFormats.RdfXml:
                graph.ToFile(RDFModelEnums.RDFFormats.RdfXml, "graphs/RdfXml.txt");
                break;

            case RDFModelEnums.RDFFormats.TriX:
                graph.ToFile(RDFModelEnums.RDFFormats.TriX, "graphs/TriX.txt");
                break;

            case RDFModelEnums.RDFFormats.Turtle:
                graph.ToFile(RDFModelEnums.RDFFormats.Turtle, "graphs/Turtle.txt");
                break;
            }
        }
コード例 #34
0
 /// <summary>
 /// Applies the query to the given graph
 /// </summary>
 public RDFConstructQueryResult ApplyToGraph(RDFGraph graph)
 => graph != null ? new RDFQueryEngine().EvaluateConstructQuery(this, graph)
                      : new RDFConstructQueryResult(this.ToString());
コード例 #35
0
        /// <summary>
        /// Given an attribute representing a RDF collection, iterates on its constituent elements
        /// to build its standard reification triples. 
        /// </summary>
        internal static void ParseCollectionElements(Uri xmlBase, XmlNode predNode, RDFResource subj,
                                                     RDFResource pred, RDFGraph result) {

            //Attach the collection as the blank object of the current pred
            RDFResource  obj              = new RDFResource();
            result.AddTriple(new RDFTriple(subj, pred, obj));

            //Iterate on the collection items to reify it
            if (predNode.HasChildNodes) {
                IEnumerator elems         = predNode.ChildNodes.GetEnumerator();
                while (elems != null && elems.MoveNext()) {
                    XmlNode elem          = (XmlNode)elems.Current;

                    //Try to get items as "rdf:about" attributes, or as "rdf:resource"
                    XmlAttribute elemUri  = 
					    (GetRdfAboutAttribute(elem) ??
                             GetRdfResourceAttribute(elem));
                    if (elemUri          != null) {

                        //Sanitize eventual blank node or relative value, depending on attribute found
                        elemUri.Value     = RDFModelUtilities.ResolveRelativeNode(elemUri, xmlBase);

                        // obj -> rdf:type -> rdf:list
                        result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.LIST));

                        // obj -> rdf:first -> res
                        result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.FIRST, new RDFResource(elemUri.Value)));

                        //Last element of a collection must give a triple to a "rdf:nil" object
                        RDFResource newObj;
                        if (elem         != predNode.ChildNodes.Item(predNode.ChildNodes.Count - 1)) {
                            // obj -> rdf:rest -> newObj
                            newObj        = new RDFResource();
                        }
                        else {
                            // obj -> rdf:rest -> rdf:nil
                            newObj        = RDFVocabulary.RDF.NIL;
                        }
                        result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.REST, newObj));
                        obj               = newObj;

                    }
                }
            }
        }
コード例 #36
0
        /// <summary>
        /// Merges the given graph into the store within a single transaction, avoiding duplicate insertions
        /// </summary>
        public override RDFStore MergeGraph(RDFGraph graph) {
            if (graph       != null) {
                var graphCtx = new RDFContext(graph.Context);

                //Create command
                var command  = new SqlCommand("IF NOT EXISTS(SELECT 1 FROM [dbo].[Quadruples] WHERE [QuadrupleID] = @QID) BEGIN INSERT INTO [dbo].[Quadruples]([QuadrupleID], [TripleFlavor], [Context], [ContextID], [Subject], [SubjectID], [Predicate], [PredicateID], [Object], [ObjectID]) VALUES (@QID, @TFV, @CTX, @CTXID, @SUBJ, @SUBJID, @PRED, @PREDID, @OBJ, @OBJID) END", this.Connection);
                command.Parameters.Add(new SqlParameter("QID",    SqlDbType.BigInt));
                command.Parameters.Add(new SqlParameter("TFV",    SqlDbType.Int));
                command.Parameters.Add(new SqlParameter("CTX",    SqlDbType.VarChar, 1000));
                command.Parameters.Add(new SqlParameter("CTXID",  SqlDbType.BigInt));
                command.Parameters.Add(new SqlParameter("SUBJ",   SqlDbType.VarChar, 1000));
                command.Parameters.Add(new SqlParameter("SUBJID", SqlDbType.BigInt));
                command.Parameters.Add(new SqlParameter("PRED",   SqlDbType.VarChar, 1000));
                command.Parameters.Add(new SqlParameter("PREDID", SqlDbType.BigInt));
                command.Parameters.Add(new SqlParameter("OBJ",    SqlDbType.VarChar, 5000));
                command.Parameters.Add(new SqlParameter("OBJID",  SqlDbType.BigInt));

                try {

                    //Open connection
                    this.Connection.Open();
                    
                    //Prepare command
                    command.Prepare();

                    //Open transaction
                    command.Transaction = this.Connection.BeginTransaction();

                    //Iterate triples
                    foreach(var triple in graph) {
                        
                        //Valorize parameters
                        command.Parameters["QID"].Value    = RDFModelUtilities.CreateHash(graphCtx         + " " +
                                                                                          triple.Subject   + " " +
                                                                                          triple.Predicate + " " +
                                                                                          triple.Object);
                        command.Parameters["TFV"].Value    = triple.TripleFlavor;
                        command.Parameters["CTX"].Value    = graphCtx.ToString();
                        command.Parameters["CTXID"].Value  = graphCtx.PatternMemberID;
                        command.Parameters["SUBJ"].Value   = triple.Subject.ToString();
                        command.Parameters["SUBJID"].Value = triple.Subject.PatternMemberID;
                        command.Parameters["PRED"].Value   = triple.Predicate.ToString();
                        command.Parameters["PREDID"].Value = triple.Predicate.PatternMemberID;
                        command.Parameters["OBJ"].Value    = triple.Object.ToString();
                        command.Parameters["OBJID"].Value  = triple.Object.PatternMemberID;
                        
                        //Execute command
                        command.ExecuteNonQuery();
                    }

                    //Close transaction
                    command.Transaction.Commit();

                    //Close connection
                    this.Connection.Close();

                }
                catch (Exception ex) {

                    //Rollback transaction
                    command.Transaction.Rollback();

                    //Close connection
                    this.Connection.Close();

                    //Propagate exception
                    throw new RDFStoreException("Cannot insert data into SQL Server store because: " + ex.Message, ex);

                }
            }
            return this;
        }
コード例 #37
0
ファイル: RDFNTriples.cs プロジェクト: mdesalvo/RDFSharp
        /// <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);
            }
        }
コード例 #38
0
ファイル: RDFNTriples.cs プロジェクト: mdesalvo/RDFSharp
        /// <summary>
        /// Serializes the given graph to the given stream using N-Triples data format. 
        /// </summary>
        internal static void Serialize(RDFGraph graph, Stream outputStream)
        {
            try {

                #region serialize
                using (StreamWriter sw         = new StreamWriter(outputStream, Encoding.ASCII)) {
                    String tripleTemplate      = String.Empty;
                    foreach(var t             in graph) {

                        #region template
                        if (t.TripleFlavor    == RDFModelEnums.RDFTripleFlavors.SPO) {
                            tripleTemplate     = "<{SUBJ}> <{PRED}> <{OBJ}> .";
                        }
                        else {
                            if (t.Object      is RDFPlainLiteral) {
                                tripleTemplate = "<{SUBJ}> <{PRED}> \"{VAL}\"@{LANG} .";
                            }
                            else {
                                tripleTemplate = "<{SUBJ}> <{PRED}> \"{VAL}\"^^<{DTYPE}> .";
                            }
                        }
                        #endregion

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

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

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

                        #region literal
                        else {

                            tripleTemplate     = tripleTemplate.Replace("{VAL}", RDFModelUtilities.EscapeControlCharsForXML(RDFModelUtilities.Unicode_To_ASCII(((RDFLiteral)t.Object).Value.Replace("\\", "\\\\").Replace("\"", "\\\""))));
                            tripleTemplate     = tripleTemplate.Replace("\n", "\\n")
                                                               .Replace("\t", "\\t")
                                                               .Replace("\r", "\\r");

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

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

                        }
                        #endregion

                        sw.WriteLine(tripleTemplate);
                    }
                }
                #endregion

            }
            catch(Exception ex) {
                throw new RDFModelException("Cannot serialize N-Triples because: " + ex.Message, ex);
            }
        }
コード例 #39
0
 /// <summary>
 /// Merges the given graph into the store, avoiding duplicate insertions
 /// </summary>
 public override RDFStore MergeGraph(RDFGraph graph) {
     if (graph != null) {
         try {
             //Open connection
             this.Connection.Open();
             //Open transaction
             this.Commands["INSERT"].Transaction = this.Commands["INSERT"].Connection.BeginTransaction();
             //Prepare command
             this.Commands["INSERT"].Prepare();
             //Iterate graph triples
             RDFContext graphCtx     = new RDFContext(graph.Context);
             RDFQuadruple quadruple  = null;
             foreach(RDFTriple t in graph) {
                 if (t.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO) {
                     quadruple       = new RDFQuadruple(graphCtx, (RDFResource)t.Subject, (RDFResource)t.Predicate, (RDFResource)t.Object);
                 }
                 else {
                     quadruple       = new RDFQuadruple(graphCtx, (RDFResource)t.Subject, (RDFResource)t.Predicate, (RDFLiteral)t.Object);
                 }
                 //Valorize parameters
                 this.Commands["INSERT"].Parameters["QID"].Value       = quadruple.QuadrupleID;
                 this.Commands["INSERT"].Parameters["TFV"].Value       = quadruple.TripleFlavor;
                 this.Commands["INSERT"].Parameters["CTX"].Value       = quadruple.Context.ToString();
                 this.Commands["INSERT"].Parameters["CTXID"].Value     = quadruple.Context.PatternMemberID;
                 this.Commands["INSERT"].Parameters["SUBJ"].Value      = quadruple.Subject.ToString();
                 this.Commands["INSERT"].Parameters["SUBJID"].Value    = quadruple.Subject.PatternMemberID;
                 this.Commands["INSERT"].Parameters["PRED"].Value      = quadruple.Predicate.ToString();
                 this.Commands["INSERT"].Parameters["PREDID"].Value    = quadruple.Predicate.PatternMemberID;
                 this.Commands["INSERT"].Parameters["OBJ"].Value       = quadruple.Object.ToString();
                 this.Commands["INSERT"].Parameters["OBJID"].Value     = quadruple.Object.PatternMemberID;
                 //Execute command
                 this.Commands["INSERT"].ExecuteNonQuery();
             }
             //Close transaction
             this.Commands["INSERT"].Transaction.Commit();
             //Close connection
             this.Connection.Close();
         }
         catch (Exception ex) {
             //Close transaction
             this.Commands["INSERT"].Transaction.Rollback();
             //Close connection
             this.Connection.Close();
             //Propagate exception
             throw new RDFStoreException("Cannot insert data into SQLite store because: " + ex.Message);
         }
     }
     return this;
 }
コード例 #40
0
ファイル: RDFContainer.cs プロジェクト: Acidburn0zzz/RDFSharp
        /// <summary>
        /// Builds the reification graph of the container:
        /// Subject -> rdf:type -> [rdf:Bag|rdf:Seq|rdf:Alt] 
        /// Subject -> rdf:_N   -> RDFContainer.ITEM(N)
        /// </summary>
        public RDFGraph ReifyContainer() {
		    RDFGraph reifCont = new RDFGraph();

            //  Subject -> rdf:type -> [rdf:Bag|rdf:Seq|rdf:Alt] 
            switch (this.ContainerType) {
                case RDFModelEnums.RDFContainerTypes.Bag:
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.BAG));
                    break;
                case RDFModelEnums.RDFContainerTypes.Seq:
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.SEQ));
                    break;
                default:
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.ALT));
                    break;
            }

            //  Subject -> rdf:_N -> RDFContainer.ITEM(N)
            Int32 index = 0;
            foreach (Object item in this) {
                RDFResource ordPred = new RDFResource(RDFVocabulary.RDF.BASE_URI + "_" + (++index));
                if (this.ItemType  == RDFModelEnums.RDFItemTypes.Resource) {
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, ordPred, (RDFResource)item));
                }
                else {
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, ordPred, (RDFLiteral)item));
                }
            }

            return reifCont;
        }
コード例 #41
0
        /// <summary>
        /// Merges the given graph into the store within a single transaction, avoiding duplicate insertions
        /// </summary>
        public override RDFStore MergeGraph(RDFGraph graph) {
            if (graph       != null) {
                var graphCtx = new RDFContext(graph.Context);

                //Create command
                var command  = new MySqlCommand("INSERT IGNORE INTO Quadruples(QuadrupleID, TripleFlavor, Context, ContextID, Subject, SubjectID, Predicate, PredicateID, Object, ObjectID) VALUES (@QID, @TFV, @CTX, @CTXID, @SUBJ, @SUBJID, @PRED, @PREDID, @OBJ, @OBJID)", this.Connection);
                command.Parameters.Add(new MySqlParameter("QID",    MySqlDbType.Int64));
                command.Parameters.Add(new MySqlParameter("TFV",    MySqlDbType.Int32));
                command.Parameters.Add(new MySqlParameter("CTX",    MySqlDbType.VarChar, 1000));
                command.Parameters.Add(new MySqlParameter("CTXID",  MySqlDbType.Int64));
                command.Parameters.Add(new MySqlParameter("SUBJ",   MySqlDbType.VarChar, 1000));
                command.Parameters.Add(new MySqlParameter("SUBJID", MySqlDbType.Int64));
                command.Parameters.Add(new MySqlParameter("PRED",   MySqlDbType.VarChar, 1000));
                command.Parameters.Add(new MySqlParameter("PREDID", MySqlDbType.Int64));
                command.Parameters.Add(new MySqlParameter("OBJ",    MySqlDbType.VarChar, 5000));
                command.Parameters.Add(new MySqlParameter("OBJID",  MySqlDbType.Int64));

                try {

                    //Open connection
                    this.Connection.Open();

                    //Prepare command
                    command.Prepare();

                    //Open transaction
                    command.Transaction = this.Connection.BeginTransaction();

                    //Iterate triples
                    foreach(var triple in graph) {

                        //Valorize parameters
                        command.Parameters["QID"].Value    = RDFModelUtilities.CreateHash(graphCtx         + " " +
                                                                                          triple.Subject   + " " +
                                                                                          triple.Predicate + " " +
                                                                                          triple.Object);
                        command.Parameters["TFV"].Value    = triple.TripleFlavor;
                        command.Parameters["CTX"].Value    = graphCtx.ToString();
                        command.Parameters["CTXID"].Value  = graphCtx.PatternMemberID;
                        command.Parameters["SUBJ"].Value   = triple.Subject.ToString();
                        command.Parameters["SUBJID"].Value = triple.Subject.PatternMemberID;
                        command.Parameters["PRED"].Value   = triple.Predicate.ToString();
                        command.Parameters["PREDID"].Value = triple.Predicate.PatternMemberID;
                        command.Parameters["OBJ"].Value    = triple.Object.ToString();
                        command.Parameters["OBJID"].Value  = triple.Object.PatternMemberID;

                        //Execute command
                        command.ExecuteNonQuery();
                    }

                    //Close transaction
                    command.Transaction.Commit();

                    //Close connection
                    this.Connection.Close();

                }
                catch (Exception ex) {

                    //Rollback transaction
                    command.Transaction.Rollback();

                    //Close connection
                    this.Connection.Close();

                    //Propagate exception
                    throw new RDFStoreException("Cannot insert data into MySQL store because: " + ex.Message, ex);

                }
            }
            return this;
        }
コード例 #42
0
ファイル: RDFTurtle.cs プロジェクト: mdesalvo/RDFSharp
        /// <summary>
        /// Serializes the given graph to the given stream using Turtle data format. 
        /// </summary>
        internal static void Serialize(RDFGraph graph, Stream outputStream)
        {
            try {

                #region serialize
                using (StreamWriter sw = new StreamWriter(outputStream, Encoding.UTF8)) {

                    #region prefixes
                    //Write the namespaces collected by the graph
                    foreach(var ns in RDFModelUtilities.GetGraphNamespaces(graph).OrderBy(n => n.NamespacePrefix)) {
                        sw.WriteLine("@prefix " + ns.NamespacePrefix + ": <" + ns.NamespaceUri + ">.");
                    }
                    sw.WriteLine("@base <" + graph.Context + ">.\n");
                    #endregion

                    #region linq
                    //Group the graph's triples by subj and pred
                    var groupedList             = (from    triple in graph
                                                   orderby triple.Subject.ToString(), triple.Predicate.ToString()
                                                   group   triple by new {
                                                        subj = triple.Subject.ToString(),
                                                        pred = triple.Predicate.ToString()
                                                  });
                    var groupedListLast         = groupedList.Last();
                    #endregion

                    #region triples
                    String actualSubj           = String.Empty;
                    String abbreviatedSubj      = String.Empty;
                    String actualPred           = String.Empty;
                    String abbreviatedPred      = String.Empty;
                    const String spaceConst     = " ";
                    StringBuilder result        = new StringBuilder();

                    //Iterate over the calculated groups
                    foreach (var group in groupedList) {
                        var groupLast           = group.Last();

                        #region subj
                        //Reset the flag of subj printing for the new iteration
                        Boolean subjPrint       = false;
                        //New subj found: write the finished Turtle token to the file, then start collecting the new one
                        if (!actualSubj.Equals(group.Key.subj, StringComparison.Ordinal)) {
                            if (result.Length > 0) {
                                result.Replace(";", ".", result.Length - 4, 1);
                                sw.Write(result.ToString());
                                result.Remove(0, result.Length - 1);
                            }
                            actualSubj          = group.Key.subj;
                            actualPred          = String.Empty;
                            if (!actualSubj.StartsWith("_:")) {
                                abbreviatedSubj = AbbreviateNamespace(actualSubj);
                            }
                            else {
                                abbreviatedSubj = actualSubj;
                            }
                            result.Append(abbreviatedSubj + " ");
                            subjPrint           = true;
                        }
                        #endregion

                        #region predObjList
                        //Iterate over the triples of the current group
                        foreach (var triple in group) {

                            #region pred
                            //New pred found: collect it to the actual Turtle token.
                            if (!actualPred.Equals(triple.Predicate.ToString(), StringComparison.Ordinal)) {
                                if (!subjPrint) {
                                    result.Append(spaceConst.PadRight(abbreviatedSubj.Length + 1)); //pretty-printing spaces to align the predList
                                }
                                actualPred          = triple.Predicate.ToString();
                                abbreviatedPred     = AbbreviateNamespace(actualPred);
                                //Turtle goody for "rdf:type" shortcutting to "a"
                                if (abbreviatedPred == RDFVocabulary.RDF.PREFIX + ":type") {
                                    abbreviatedPred = "a";
                                }
                                result.Append(abbreviatedPred + " ");
                            }
                            #endregion

                            #region object
                            //Collect the object or the literal to the Turtle token
                            if (triple.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO) {
                                String obj           = triple.Object.ToString();
                                if (!obj.StartsWith("_:")) {
                                     result.Append(AbbreviateNamespace(obj));
                                }
                                else {
                                     result.Append(obj);
                                }
                            }
                            #endregion

                            #region literal
                            else {

                                //Detect presence of long-literals
                                var litValDelim = "\"";
                                if (regexTTL.Match(triple.Object.ToString()).Success) {
                                    litValDelim = "\"\"\"";
                                }

                                if (triple.Object is RDFTypedLiteral) {
                                    String tLit = litValDelim + ((RDFTypedLiteral)triple.Object).Value.Replace("\\","\\\\") + litValDelim + "^^" + AbbreviateNamespace(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)triple.Object).Datatype));
                                    result.Append(tLit);
                                }
                                else {
                                    String pLit = litValDelim + ((RDFPlainLiteral)triple.Object).Value.Replace("\\","\\\\") + litValDelim;
                                    if (((RDFPlainLiteral)triple.Object).Language != String.Empty) {
                                        pLit    = pLit + "@"  + ((RDFPlainLiteral)triple.Object).Language;
                                    }
                                    result.Append(pLit);
                                }

                            }
                            #endregion

                            #region continuation goody
                            //Then append the appropriated Turtle continuation goody ("," or ";")
                            if (!triple.Equals(groupLast)) {
                                result.Append(", ");
                            }
                            else {
                                result.AppendLine("; ");
                            }
                            #endregion

                        }
                        #endregion

                        #region last group
                        //This is only for the last group, which is not written into the cycle as the others
                        if (group.Key.Equals(groupedListLast.Key)) {
                            result.Replace(";", ".", result.Length - 4, 1);
                            sw.Write(result.ToString());
                        }
                        #endregion

                    }
                    #endregion

                }
                #endregion

            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot serialize Turtle because: " + ex.Message, ex);
            }
        }
コード例 #43
0
ファイル: RDFTurtle.cs プロジェクト: mdesalvo/RDFSharp
 /// <summary>
 /// Serializes the given graph to the given filepath using Turtle data format. 
 /// </summary>
 internal static void Serialize(RDFGraph graph, String filepath)
 {
     Serialize(graph, new FileStream(filepath, FileMode.Create));
 }
コード例 #44
0
        /// <summary>
        /// Selects the triples corresponding to the given pattern from the given graph
        /// </summary>
        internal static List<RDFTriple> SelectTriples(RDFGraph graph,  RDFResource subj, 
                                                                       RDFResource pred, 
                                                                       RDFResource obj, 
                                                                       RDFLiteral  lit) {
            var matchSubj        = new List<RDFTriple>();
            var matchPred        = new List<RDFTriple>();
            var matchObj         = new List<RDFTriple>();
            var matchLit         = new List<RDFTriple>();
            var matchResult      = new List<RDFTriple>();
            if (graph           != null) {
                
                //Filter by Subject
                if (subj        != null) {
                    foreach (var t in graph.GraphIndex.SelectIndexBySubject(subj).Keys) {
                        matchSubj.Add(graph.Triples[t]);
                    }
                }

                //Filter by Predicate
                if (pred        != null) {
                    foreach (var t in graph.GraphIndex.SelectIndexByPredicate(pred).Keys) {
                        matchPred.Add(graph.Triples[t]);
                    }
                }

                //Filter by Object
                if (obj         != null) {
                    foreach (var t in graph.GraphIndex.SelectIndexByObject(obj).Keys) {
                        matchObj.Add(graph.Triples[t]);
                    }
                }

                //Filter by Literal
                if (lit         != null) {
                    foreach (var t in graph.GraphIndex.SelectIndexByLiteral(lit).Keys) {
                        matchLit.Add(graph.Triples[t]);
                    }
                }

                //Intersect the filters
                if (subj                   != null) {
                    if (pred               != null) {
                        if (obj            != null) {
                            //S->P->O
                            matchResult     = matchSubj.Intersect(matchPred)
                                                       .Intersect(matchObj)
                                                       .ToList<RDFTriple>();
                        }
                        else {
                            if (lit        != null) {
                                //S->P->L
                                matchResult = matchSubj.Intersect(matchPred)
                                                       .Intersect(matchLit)
                                                       .ToList<RDFTriple>();
                            }
                            else {
                                //S->P->
                                matchResult = matchSubj.Intersect(matchPred)
                                                       .ToList<RDFTriple>();
                            }
                        }
                    }
                    else {
                        if (obj            != null) {
                            //S->->O
                            matchResult     = matchSubj.Intersect(matchObj)
                                                       .ToList<RDFTriple>();
                        }
                        else {
                            if (lit        != null) {
                                //S->->L
                                matchResult = matchSubj.Intersect(matchLit)
                                                       .ToList<RDFTriple>();
                            }
                            else {
                                //S->->
                                matchResult = matchSubj;
                            }
                        }
                    }
                }
                else {
                    if (pred               != null) {
                        if (obj            != null) {
                            //->P->O
                            matchResult     = matchPred.Intersect(matchObj)
                                                       .ToList<RDFTriple>();
                        }
                        else {
                            if (lit        != null) {
                                //->P->L
                                matchResult = matchPred.Intersect(matchLit)
                                                       .ToList<RDFTriple>();
                            }
                            else {
                                //->P->
                                matchResult = matchPred;
                            }
                        }
                    }
                    else {
                        if (obj            != null) {
                            //->->O
                            matchResult     = matchObj;
                        }
                        else {
                            if (lit        != null) {
                                //->->L
                                matchResult = matchLit;
                            }
                            else {
                                //->->
                                matchResult = graph.Triples.Values.ToList<RDFTriple>();
                            }
                        }
                    }
                }

            }
            return matchResult;
        }
コード例 #45
0
        /// <summary>
        /// Gives the subj node extracted from the attribute list of the current element 
        /// </summary>
        internal static RDFResource GetSubjectNode(XmlNode subjNode, Uri xmlBase, RDFGraph result) {
            RDFResource subj             = null;

            //If there are attributes, search them for the one representing the subj
            if (subjNode.Attributes     != null && subjNode.Attributes.Count > 0) {

                //We are interested in finding the "rdf:about" node for the subj
                XmlAttribute rdfAbout    = GetRdfAboutAttribute(subjNode);
                if (rdfAbout != null) {
                    //Attribute found, but we must check if it is "rdf:ID", "rdf:nodeID" or a relative Uri: 
                    //in this case it must be resolved against the xmlBase namespace, or else it remains the same
                    String rdfAboutValue = RDFModelUtilities.ResolveRelativeNode(rdfAbout, xmlBase);
                    subj      = new RDFResource(rdfAboutValue);
                }

                //If "rdf:about" attribute has been found for the subj, we must
                //check if the node is not a standard "rdf:Description": this is
                //the case we can directly build a triple with "rdf:type" pred
                if (subj     != null && !CheckIfRdfDescriptionNode(subjNode)) {
                    RDFResource obj      = null;
                    if (subjNode.NamespaceURI == String.Empty) {
                        obj   = new RDFResource(xmlBase + subjNode.LocalName);
                    }
                    else {
                        obj   = new RDFResource(subjNode.NamespaceURI + subjNode.LocalName);
                    }
                    result.AddTriple(new RDFTriple(subj, RDFVocabulary.RDF.TYPE, obj));
                }

            }

            //There are no attributes, so there's only one way we can handle this element:
            //if it is a standard rdf:Description, it is a blank Subject
            else {
                if (CheckIfRdfDescriptionNode(subjNode)) {
                    subj      = new RDFResource();
                }
            }

            return subj;
        }
コード例 #46
0
        /// <summary>
        /// Serializes the given graph to the given filepath using TriX data format. 
        /// </summary>
        internal static void Serialize(RDFGraph graph, String filepath) {
            try {

                #region serialize
                using (XmlTextWriter trixWriter = new XmlTextWriter(filepath, 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(RDFTriple t in graph) {
                        XmlNode tripleElement   = trixDoc.CreateNode(XmlNodeType.Element, "triple", null);

                        #region subj
                        XmlNode subjElement     = null;
                        XmlText subjElementText = null;
                        if (((RDFResource)t.Subject).IsBlank) {
                            subjElement         = trixDoc.CreateNode(XmlNodeType.Element, "id", null);
                            subjElementText     = trixDoc.CreateTextNode(t.Subject.ToString().Replace("bnode:", String.Empty));
                        }
                        else {
                            subjElement         = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                            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     = null;
                            XmlText objElementText = null;
                            if (((RDFResource)t.Object).IsBlank)  {
                                objElement         = trixDoc.CreateNode(XmlNodeType.Element, "id", null);
                                objElementText     = trixDoc.CreateTextNode(t.Object.ToString().Replace("bnode:", String.Empty));
                            }
                            else  {
                                objElement         = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                                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(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(((RDFTypedLiteral)t.Object).Datatype.ToString());
                                datatype.AppendChild(datatypeText);
                                typedLiteralElement.Attributes.Append(datatype);
                                XmlText typedLiteralText    = trixDoc.CreateTextNode(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);
            }
        }
コード例 #47
0
        /// <summary>
        /// Given an element representing a RDF container, iterates on its constituent elements
        /// to build its standard reification triples. 
        /// </summary>
        internal static void ParseContainerElements(RDFModelEnums.RDFContainerTypes contType, XmlNode container,
                                                    RDFResource subj, RDFResource pred, RDFGraph result) {

            //Attach the container as the blank object of the current pred
            RDFResource  obj                 = new RDFResource();
            result.AddTriple(new RDFTriple(subj, pred, obj));

            //obj -> rdf:type -> rdf:[Bag|Seq|Alt]
            switch (contType) {
                case RDFModelEnums.RDFContainerTypes.Bag:
                    result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.BAG));
                    break;
                case RDFModelEnums.RDFContainerTypes.Seq:
                    result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.SEQ));
                    break;
                default:
                    result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.ALT));
                    break;
            }

            //Iterate on the container items
            if (container.HasChildNodes) {
                IEnumerator elems              = container.ChildNodes.GetEnumerator();
                List<String> elemVals          = new List<String>();
                while (elems != null && elems.MoveNext()) {
                    XmlNode elem               = (XmlNode)elems.Current;
                    XmlAttribute elemUri       = GetRdfResourceAttribute(elem);

                    #region Container Resource Item
                    //This is a container of resources
                    if (elemUri               != null) {

                        //Sanitize eventual blank node value detected by presence of "nodeID" attribute
                        if (elemUri.LocalName.Equals("nodeID", StringComparison.Ordinal)) {
                            if (!elemUri.Value.StartsWith("bnode:")) {
                                 elemUri.Value = "bnode:" + elemUri.Value;
                            }
                        }

                        //obj -> rdf:_N -> VALUE 
                        if (contType          == RDFModelEnums.RDFContainerTypes.Alt) {
                            if (!elemVals.Contains(elemUri.Value)) {
                                elemVals.Add(elemUri.Value);
                                result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value)));
                            }
                        }
                        else {
                            result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value)));
                        }

                    }
                    #endregion

                    #region Container Literal Item
                    //This is a container of literals
                    else {

                        //Parse the literal contained in the item
                        RDFLiteral literal     = null;
                        XmlAttribute attr      = GetRdfDatatypeAttribute(elem);
                        if (attr              != null) {
                            literal            = new RDFTypedLiteral(elem.InnerText, RDFModelUtilities.GetDatatypeFromString(attr.InnerText));
                        }
                        else {
                            attr               = GetXmlLangAttribute(elem);
                            literal            = new RDFPlainLiteral(elem.InnerText, (attr != null ? attr.InnerText : String.Empty));
                        }

                        //obj -> rdf:_N -> VALUE 
                        if (contType          == RDFModelEnums.RDFContainerTypes.Alt) {
                            if (!elemVals.Contains(literal.ToString())) {
                                 elemVals.Add(literal.ToString());
                                 result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal));
                            }
                        }
                        else {
                            result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal));
                        }

                    }
                    #endregion

                }
            }

        }
コード例 #48
0
ファイル: RDFXml.cs プロジェクト: Acidburn0zzz/RDFSharp
        /// <summary>
        /// Deserializes the given Xml filepath to a graph. 
        /// </summary>
        internal static RDFGraph Deserialize(String filepath) {
            try {

                #region deserialize
                XmlReaderSettings xrs    = new XmlReaderSettings(); 
                xrs.IgnoreComments       = true;
                xrs.DtdProcessing        = DtdProcessing.Ignore;

                RDFGraph result          = new RDFGraph();
                using(XmlReader xr       = XmlReader.Create(new StreamReader(filepath, Encoding.UTF8), xrs)) {

                    #region load
                    XmlDocument xmlDoc   = new XmlDocument();
                    xmlDoc.Load(xr);
                    #endregion

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

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

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

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

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

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

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

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

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

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

                                }
                            }
                            #endregion

                        }
                    }
                    #endregion

                }
                return result;
                #endregion

            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize Xml because: " + ex.Message, ex);
            }
        }
コード例 #49
0
        /// <summary>
        /// Applies the query to the given graph 
        /// </summary>
        public RDFSelectQueryResult ApplyToGraph(RDFGraph graph) {
            if (graph != null) {
                this.PatternGroupResultTables.Clear();
                this.PatternResultTables.Clear();

                RDFSelectQueryResult selectResult    = new RDFSelectQueryResult(this.ToString());
                if (!this.IsEmpty) {

                    //Iterate the pattern groups of the query
                    foreach (RDFPatternGroup patternGroup in this.PatternGroups) {

                        //Step 1: Get the intermediate result tables of the current pattern group
                        RDFSelectQueryEngine.EvaluatePatterns(this, patternGroup, graph);

                        //Step 2: Get the result table of the current pattern group
                        RDFSelectQueryEngine.CombinePatterns(this, patternGroup);

                        //Step 3: Apply the filters of the current pattern group to its result table
                        RDFSelectQueryEngine.ApplyFilters(this, patternGroup);

                    }

                    //Step 4: Get the result table of the query
                    DataTable queryResultTable       = RDFQueryEngine.CombineTables(this.PatternGroupResultTables.Values.ToList<DataTable>(), false);

                    //Step 5: Apply the modifiers of the query to the result table
                    selectResult.SelectResults       = RDFSelectQueryEngine.ApplyModifiers(this, queryResultTable);

                }

                return selectResult;
            }
            throw new RDFQueryException("Cannot execute SELECT query because given \"graph\" parameter is null.");
        }
コード例 #50
0
        /// <summary>
        /// Gets the list of namespaces used within the triples of the given graph
        /// </summary>
        internal static List<RDFNamespace> GetGraphNamespaces(RDFGraph graph)
        {
            var result     = new List<RDFNamespace>();
            foreach (var   t in graph) {
                var subj   = t.Subject.ToString();
                var pred   = t.Predicate.ToString();
                var obj    = t.Object is RDFResource ? t.Object.ToString() :
                                (t.Object is RDFTypedLiteral ? GetDatatypeFromEnum(((RDFTypedLiteral)t.Object).Datatype) : String.Empty);

                //Resolve subject Uri
                var subjNS = RDFNamespaceRegister.Instance.Register.Where(x => subj.StartsWith(x.ToString()));

                //Resolve predicate Uri
                var predNS = RDFNamespaceRegister.Instance.Register.Where(x => pred.StartsWith(x.ToString()));

                //Resolve object Uri
                var objNS  = RDFNamespaceRegister.Instance.Register.Where(x => obj.StartsWith(x.ToString()));

                result.AddRange(subjNS);
                result.AddRange(predNS);
                result.AddRange(objNS);
            }
            return result.Distinct().ToList();
        }
コード例 #51
0
        /// <summary>
        /// Applies the query to the given graph 
        /// </summary>
        public RDFConstructQueryResult ApplyToGraph(RDFGraph graph)
        {
            if (graph != null) {
                this.PatternGroupResultTables.Clear();
                this.PatternResultTables.Clear();

                RDFConstructQueryResult constructResult = new RDFConstructQueryResult(this.ToString());
                if (this.PatternGroups.Any()) {

                    //Iterate the pattern groups of the query
                    foreach (RDFPatternGroup patternGroup in this.PatternGroups) {

                        //Step 1: Get the intermediate result tables of the current pattern group
                        RDFQueryEngine.EvaluatePatterns(this, patternGroup, graph);

                        //Step 2: Get the result table of the current pattern group
                        RDFQueryEngine.CombinePatterns(this, patternGroup);

                        //Step 3: Apply the filters of the current pattern group to its result table
                        RDFQueryEngine.ApplyFilters(this, patternGroup);

                    }

                    //Step 4: Get the result table of the query
                    DataTable queryResultTable          = RDFQueryEngine.CombineTables(this.PatternGroupResultTables.Values.ToList(), false);

                    //Step 5: Fill the templates from the result table
                    DataTable filledResultTable         = RDFQueryEngine.FillTemplates(this, queryResultTable);

                    //Step 6: Apply the modifiers of the query to the result table
                    constructResult.ConstructResults    = RDFQueryEngine.ApplyModifiers(this, filledResultTable);

                }

                return constructResult;
            }
            throw new RDFQueryException("Cannot execute CONSTRUCT query because given \"graph\" parameter is null.");
        }
コード例 #52
0
ファイル: RdfViewer.aspx.cs プロジェクト: smoore4moma/tms-rdf
        protected void LoadRDF()
        {
            // First we set some core RDF resources
            // agent refers to artist(s)
            RDFResource type = RDFVocabulary.RDF.TYPE;
            RDFResource name = RDFVocabulary.FOAF.NAME;
            RDFResource agent = RDFVocabulary.FOAF.AGENT;

            // TGN is a Getty vocabulary for locations
            // TGN added to RDFSharp vocabularies manually.  TGN ID is stored in TMSThes (or equivalent in TMS 2014+)
            RDFResource tgn = new RDFResource(RDFVocabulary.TGN.BASE_URI);

            // The predicates below are often part of ULAN (which we don't have)
            // unsure if using bio events this way is acceptable...

            RDFResource livedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/livedIn");
            RDFResource activeIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/activeIn");
            RDFResource educatedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/educatedIn");
            RDFResource bornIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/bornIn");
            RDFResource diedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/diedIn");

            RDFResource anUri = new RDFResource("http://example.org/uris#anUri");

            // The following entries are all generated from SQL queries which you can find in the file SQL.txt  Technically we could load them into the database directly,
            // but this allows us to see how a resource is "built" and it creates the correct RDF format files (NTriples, RdfXml, TriX), as well as inserts into the db.
            // Once in the db, we do not need to run LoadRDF() except to refresh data.

            #region Artists (agents)
            // Ideally this would reference the Getty vocabulary for ULAN but we don't have the ULAN ID stored in the db
            RDFResource raimundabraham = new RDFResource("http://example.org/artists/47");
            RDFResource emilioambasz = new RDFResource("http://example.org/artists/141");
            RDFResource mariobotta = new RDFResource("http://example.org/artists/696");
            RDFResource louisikahn = new RDFResource("http://example.org/artists/2964");
            RDFResource frederickkiesler = new RDFResource("http://example.org/artists/3091");
            RDFResource leonkrier = new RDFResource("http://example.org/artists/3250");
            RDFResource masayukikurokawa = new RDFResource("http://example.org/artists/3308");
            RDFResource ernestobrunolapadula = new RDFResource("http://example.org/artists/3381");
            RDFResource richardmeier = new RDFResource("http://example.org/artists/3910");
            RDFResource eerosaarinen = new RDFResource("http://example.org/artists/5103");
            RDFResource franklloydwright = new RDFResource("http://example.org/artists/6459");
            RDFResource evazeisel = new RDFResource("http://example.org/artists/6556");
            RDFResource zahahadid = new RDFResource("http://example.org/artists/6953");
            RDFResource santiagocalatrava = new RDFResource("http://example.org/artists/6968");
            RDFResource tadaoando = new RDFResource("http://example.org/artists/7055");
            RDFResource ludwigmiesvanderrohe = new RDFResource("http://example.org/artists/7166");
            RDFResource rafaelviñoly = new RDFResource("http://example.org/artists/7229");
            RDFResource aldorossi = new RDFResource("http://example.org/artists/7661");
            RDFResource simonungers = new RDFResource("http://example.org/artists/7992");
            RDFResource giovanniguerrini = new RDFResource("http://example.org/artists/8157");
            RDFResource marioromano = new RDFResource("http://example.org/artists/8158");
            RDFResource thommayne = new RDFResource("http://example.org/artists/8218");
            RDFResource thomaskinslow = new RDFResource("http://example.org/artists/8248");
            RDFResource fusogomuindcoltdtokyo = new RDFResource("http://example.org/artists/9029");
            RDFResource hallchinacoeastliverpooloh = new RDFResource("http://example.org/artists/10013");
            RDFResource andrewzago = new RDFResource("http://example.org/artists/22884");
            RDFResource morphosissantamonicaca = new RDFResource("http://example.org/artists/29711");

            // Artists(agents): plain literal name

            RDFPlainLiteral aldorossiName = new RDFPlainLiteral("Aldo Rossi");
            RDFPlainLiteral andrewzagoName = new RDFPlainLiteral("Andrew Zago");
            RDFPlainLiteral eerosaarinenName = new RDFPlainLiteral("Eero Saarinen");
            RDFPlainLiteral emilioambaszName = new RDFPlainLiteral("Emilio Ambasz");
            RDFPlainLiteral ernestobrunolapadulaName = new RDFPlainLiteral("Ernesto Bruno La Padula");
            RDFPlainLiteral evazeiselName = new RDFPlainLiteral("Eva Zeisel");
            RDFPlainLiteral franklloydwrightName = new RDFPlainLiteral("Frank Lloyd Wright");
            RDFPlainLiteral frederickkieslerName = new RDFPlainLiteral("Frederick Kiesler");
            RDFPlainLiteral fusogomuindcoltdtokyoName = new RDFPlainLiteral("Fuso Gomu Ind. Co., Ltd., Tokyo");
            RDFPlainLiteral giovanniguerriniName = new RDFPlainLiteral("Giovanni Guerrini");
            RDFPlainLiteral hallchinacoeastliverpoolohName = new RDFPlainLiteral("Hall China Co., East Liverpool, OH");
            RDFPlainLiteral leonkrierName = new RDFPlainLiteral("Leon Krier");
            RDFPlainLiteral louisikahnName = new RDFPlainLiteral("Louis I. Kahn");
            RDFPlainLiteral ludwigmiesvanderroheName = new RDFPlainLiteral("Ludwig Mies van der Rohe");
            RDFPlainLiteral mariobottaName = new RDFPlainLiteral("Mario Botta");
            RDFPlainLiteral marioromanoName = new RDFPlainLiteral("Mario Romano");
            RDFPlainLiteral masayukikurokawaName = new RDFPlainLiteral("Masayuki Kurokawa");
            RDFPlainLiteral morphosissantamonicacaName = new RDFPlainLiteral("Morphosis, Santa Monica, CA");
            RDFPlainLiteral rafaelviñolyName = new RDFPlainLiteral("Rafael Viñoly");
            RDFPlainLiteral raimundabrahamName = new RDFPlainLiteral("Raimund Abraham");
            RDFPlainLiteral richardmeierName = new RDFPlainLiteral("Richard Meier");
            RDFPlainLiteral santiagocalatravaName = new RDFPlainLiteral("Santiago Calatrava");
            RDFPlainLiteral simonungersName = new RDFPlainLiteral("Simon Ungers");
            RDFPlainLiteral tadaoandoName = new RDFPlainLiteral("Tadao Ando");
            RDFPlainLiteral thommayneName = new RDFPlainLiteral("Thom Mayne");
            RDFPlainLiteral thomaskinslowName = new RDFPlainLiteral("Thomas Kinslow");
            RDFPlainLiteral zahahadidName = new RDFPlainLiteral("Zaha Hadid");

            #endregion

            #region Locations (tgn)

            RDFResource northwales = new RDFResource("http://vocab.getty.edu/tgn/2091433-place");
            RDFResource wales = new RDFResource("http://vocab.getty.edu/tgn/7002443-place");
            RDFResource berlin = new RDFResource("http://vocab.getty.edu/tgn/7003712-place");
            RDFResource newyork = new RDFResource("http://vocab.getty.edu/tgn/7007567-place");
            RDFResource edinburgh = new RDFResource("http://vocab.getty.edu/tgn/7009546-place");
            RDFResource kiyev = new RDFResource("http://vocab.getty.edu/tgn/7010171-place");
            RDFResource london = new RDFResource("http://vocab.getty.edu/tgn/7011781-place");
            RDFResource moskva = new RDFResource("http://vocab.getty.edu/tgn/7012974-place");
            RDFResource boston = new RDFResource("http://vocab.getty.edu/tgn/7013445-place");
            RDFResource detroit = new RDFResource("http://vocab.getty.edu/tgn/7013547-place");
            RDFResource longbeach = new RDFResource("http://vocab.getty.edu/tgn/7013905-place");
            RDFResource sanfrancisco = new RDFResource("http://vocab.getty.edu/tgn/7014456-place");

            // Locations (tgn): plain literal name

            RDFPlainLiteral berlinName = new RDFPlainLiteral("Berlin");
            RDFPlainLiteral bostonName = new RDFPlainLiteral("Boston");
            RDFPlainLiteral detroitName = new RDFPlainLiteral("Detroit");
            RDFPlainLiteral edinburghName = new RDFPlainLiteral("Edinburgh");
            RDFPlainLiteral kiyevName = new RDFPlainLiteral("Kiyev");
            RDFPlainLiteral londonName = new RDFPlainLiteral("London");
            RDFPlainLiteral longbeachName = new RDFPlainLiteral("Long Beach");
            RDFPlainLiteral moskvaName = new RDFPlainLiteral("Moskva");
            RDFPlainLiteral newyorkName = new RDFPlainLiteral("New York");
            RDFPlainLiteral northwalesName = new RDFPlainLiteral("North Wales");
            RDFPlainLiteral sanfranciscoName = new RDFPlainLiteral("San Francisco");
            RDFPlainLiteral walesName = new RDFPlainLiteral("Wales");

            #endregion

            #region Triples

            // Create triple resources

            RDFTriple aldorossi_type_agent = new RDFTriple(aldorossi, type, agent);
            RDFTriple andrewzago_type_agent = new RDFTriple(andrewzago, type, agent);
            RDFTriple eerosaarinen_type_agent = new RDFTriple(eerosaarinen, type, agent);
            RDFTriple emilioambasz_type_agent = new RDFTriple(emilioambasz, type, agent);
            RDFTriple ernestobrunolapadula_type_agent = new RDFTriple(ernestobrunolapadula, type, agent);
            RDFTriple evazeisel_type_agent = new RDFTriple(evazeisel, type, agent);
            RDFTriple franklloydwright_type_agent = new RDFTriple(franklloydwright, type, agent);
            RDFTriple frederickkiesler_type_agent = new RDFTriple(frederickkiesler, type, agent);
            RDFTriple fusogomuindcoltdtokyo_type_agent = new RDFTriple(fusogomuindcoltdtokyo, type, agent);
            RDFTriple giovanniguerrini_type_agent = new RDFTriple(giovanniguerrini, type, agent);
            RDFTriple hallchinacoeastliverpooloh_type_agent = new RDFTriple(hallchinacoeastliverpooloh, type, agent);
            RDFTriple leonkrier_type_agent = new RDFTriple(leonkrier, type, agent);
            RDFTriple louisikahn_type_agent = new RDFTriple(louisikahn, type, agent);
            RDFTriple ludwigmiesvanderrohe_type_agent = new RDFTriple(ludwigmiesvanderrohe, type, agent);
            RDFTriple mariobotta_type_agent = new RDFTriple(mariobotta, type, agent);
            RDFTriple marioromano_type_agent = new RDFTriple(marioromano, type, agent);
            RDFTriple masayukikurokawa_type_agent = new RDFTriple(masayukikurokawa, type, agent);
            RDFTriple morphosissantamonicaca_type_agent = new RDFTriple(morphosissantamonicaca, type, agent);
            RDFTriple rafaelviñoly_type_agent = new RDFTriple(rafaelviñoly, type, agent);
            RDFTriple raimundabraham_type_agent = new RDFTriple(raimundabraham, type, agent);
            RDFTriple richardmeier_type_agent = new RDFTriple(richardmeier, type, agent);
            RDFTriple santiagocalatrava_type_agent = new RDFTriple(santiagocalatrava, type, agent);
            RDFTriple simonungers_type_agent = new RDFTriple(simonungers, type, agent);
            RDFTriple tadaoando_type_agent = new RDFTriple(tadaoando, type, agent);
            RDFTriple thommayne_type_agent = new RDFTriple(thommayne, type, agent);
            RDFTriple thomaskinslow_type_agent = new RDFTriple(thomaskinslow, type, agent);
            RDFTriple zahahadid_type_agent = new RDFTriple(zahahadid, type, agent);

            RDFTriple berlin_type_tgn = new RDFTriple(berlin, type, tgn);
            RDFTriple boston_type_tgn = new RDFTriple(boston, type, tgn);
            RDFTriple detroit_type_tgn = new RDFTriple(detroit, type, tgn);
            RDFTriple edinburgh_type_tgn = new RDFTriple(edinburgh, type, tgn);
            RDFTriple kiyev_type_tgn = new RDFTriple(kiyev, type, tgn);
            RDFTriple london_type_tgn = new RDFTriple(london, type, tgn);
            RDFTriple longbeach_type_tgn = new RDFTriple(longbeach, type, tgn);
            RDFTriple moskva_type_tgn = new RDFTriple(moskva, type, tgn);
            RDFTriple newyork_type_tgn = new RDFTriple(newyork, type, tgn);
            RDFTriple northwales_type_tgn = new RDFTriple(northwales, type, tgn);
            RDFTriple sanfrancisco_type_tgn = new RDFTriple(sanfrancisco, type, tgn);
            RDFTriple wales_type_tgn = new RDFTriple(wales, type, tgn);

            RDFTriple aldorossi_name_aldorossiName = new RDFTriple(aldorossi, name, aldorossiName);
            RDFTriple andrewzago_name_andrewzagoName = new RDFTriple(andrewzago, name, andrewzagoName);
            RDFTriple eerosaarinen_name_eerosaarinenName = new RDFTriple(eerosaarinen, name, eerosaarinenName);
            RDFTriple emilioambasz_name_emilioambaszName = new RDFTriple(emilioambasz, name, emilioambaszName);
            RDFTriple ernestobrunolapadula_name_ernestobrunolapadulaName = new RDFTriple(ernestobrunolapadula, name, ernestobrunolapadulaName);
            RDFTriple evazeisel_name_evazeiselName = new RDFTriple(evazeisel, name, evazeiselName);
            RDFTriple franklloydwright_name_franklloydwrightName = new RDFTriple(franklloydwright, name, franklloydwrightName);
            RDFTriple frederickkiesler_name_frederickkieslerName = new RDFTriple(frederickkiesler, name, frederickkieslerName);
            RDFTriple fusogomuindcoltdtokyo_name_fusogomuindcoltdtokyoName = new RDFTriple(fusogomuindcoltdtokyo, name, fusogomuindcoltdtokyoName);
            RDFTriple giovanniguerrini_name_giovanniguerriniName = new RDFTriple(giovanniguerrini, name, giovanniguerriniName);
            RDFTriple hallchinacoeastliverpooloh_name_hallchinacoeastliverpoolohName = new RDFTriple(hallchinacoeastliverpooloh, name, hallchinacoeastliverpoolohName);
            RDFTriple leonkrier_name_leonkrierName = new RDFTriple(leonkrier, name, leonkrierName);
            RDFTriple louisikahn_name_louisikahnName = new RDFTriple(louisikahn, name, louisikahnName);
            RDFTriple ludwigmiesvanderrohe_name_ludwigmiesvanderroheName = new RDFTriple(ludwigmiesvanderrohe, name, ludwigmiesvanderroheName);
            RDFTriple mariobotta_name_mariobottaName = new RDFTriple(mariobotta, name, mariobottaName);
            RDFTriple marioromano_name_marioromanoName = new RDFTriple(marioromano, name, marioromanoName);
            RDFTriple masayukikurokawa_name_masayukikurokawaName = new RDFTriple(masayukikurokawa, name, masayukikurokawaName);
            RDFTriple morphosissantamonicaca_name_morphosissantamonicacaName = new RDFTriple(morphosissantamonicaca, name, morphosissantamonicacaName);
            RDFTriple rafaelviñoly_name_rafaelviñolyName = new RDFTriple(rafaelviñoly, name, rafaelviñolyName);
            RDFTriple raimundabraham_name_raimundabrahamName = new RDFTriple(raimundabraham, name, raimundabrahamName);
            RDFTriple richardmeier_name_richardmeierName = new RDFTriple(richardmeier, name, richardmeierName);
            RDFTriple santiagocalatrava_name_santiagocalatravaName = new RDFTriple(santiagocalatrava, name, santiagocalatravaName);
            RDFTriple simonungers_name_simonungersName = new RDFTriple(simonungers, name, simonungersName);
            RDFTriple tadaoando_name_tadaoandoName = new RDFTriple(tadaoando, name, tadaoandoName);
            RDFTriple thommayne_name_thommayneName = new RDFTriple(thommayne, name, thommayneName);
            RDFTriple thomaskinslow_name_thomaskinslowName = new RDFTriple(thomaskinslow, name, thomaskinslowName);
            RDFTriple zahahadid_name_zahahadidName = new RDFTriple(zahahadid, name, zahahadidName);

            RDFTriple berlin_name_berlinName = new RDFTriple(berlin, name, berlinName);
            RDFTriple boston_name_bostonName = new RDFTriple(boston, name, bostonName);
            RDFTriple detroit_name_detroitName = new RDFTriple(detroit, name, detroitName);
            RDFTriple edinburgh_name_edinburghName = new RDFTriple(edinburgh, name, edinburghName);
            RDFTriple kiyev_name_kiyevName = new RDFTriple(kiyev, name, kiyevName);
            RDFTriple london_name_londonName = new RDFTriple(london, name, londonName);
            RDFTriple longbeach_name_longbeachName = new RDFTriple(longbeach, name, longbeachName);
            RDFTriple moskva_name_moskvaName = new RDFTriple(moskva, name, moskvaName);
            RDFTriple newyork_name_newyorkName = new RDFTriple(newyork, name, newyorkName);
            RDFTriple northwales_name_northwalesName = new RDFTriple(northwales, name, northwalesName);
            RDFTriple sanfrancisco_name_sanfranciscoName = new RDFTriple(sanfrancisco, name, sanfranciscoName);
            RDFTriple wales_name_walesName = new RDFTriple(wales, name, walesName);

            RDFTriple aldorossi_activeIn_moskva = new RDFTriple(aldorossi, activeIn, moskva);
            RDFTriple andrewzago_activeIn_moskva = new RDFTriple(andrewzago, activeIn, moskva);
            RDFTriple eerosaarinen_activeIn_newyork = new RDFTriple(eerosaarinen, activeIn, newyork);
            RDFTriple emilioambasz_activeIn_newyork = new RDFTriple(emilioambasz, activeIn, newyork);
            RDFTriple ernestobrunolapadula_activeIn_newyork = new RDFTriple(ernestobrunolapadula, activeIn, newyork);
            RDFTriple evazeisel_educatedIn_berlin = new RDFTriple(evazeisel, educatedIn, berlin);
            RDFTriple franklloydwright_activeIn_detroit = new RDFTriple(franklloydwright, activeIn, detroit);
            RDFTriple franklloydwright_livedIn_moskva = new RDFTriple(franklloydwright, livedIn, moskva);
            RDFTriple frederickkiesler_livedIn_longbeach = new RDFTriple(frederickkiesler, livedIn, longbeach);
            RDFTriple fusogomuindcoltdtokyo_livedIn_london = new RDFTriple(fusogomuindcoltdtokyo, livedIn, london);
            RDFTriple giovanniguerrini_activeIn_newyork = new RDFTriple(giovanniguerrini, activeIn, newyork);
            RDFTriple hallchinacoeastliverpooloh_educatedIn_berlin = new RDFTriple(hallchinacoeastliverpooloh, educatedIn, berlin);
            RDFTriple leonkrier_activeIn_newyork = new RDFTriple(leonkrier, activeIn, newyork);
            RDFTriple leonkrier_educatedIn_london = new RDFTriple(leonkrier, educatedIn, london);
            RDFTriple louisikahn_livedIn_longbeach = new RDFTriple(louisikahn, livedIn, longbeach);
            RDFTriple louisikahn_livedIn_newyork = new RDFTriple(louisikahn, livedIn, newyork);
            RDFTriple ludwigmiesvanderrohe_activeIn_moskva = new RDFTriple(ludwigmiesvanderrohe, activeIn, moskva);
            RDFTriple ludwigmiesvanderrohe_livedIn_moskva = new RDFTriple(ludwigmiesvanderrohe, livedIn, moskva);
            RDFTriple mariobotta_activeIn_kiyev = new RDFTriple(mariobotta, activeIn, kiyev);
            RDFTriple mariobotta_activeIn_moskva = new RDFTriple(mariobotta, activeIn, moskva);
            RDFTriple mariobotta_livedIn_moskva = new RDFTriple(mariobotta, livedIn, moskva);
            RDFTriple marioromano_activeIn_newyork = new RDFTriple(marioromano, activeIn, newyork);
            RDFTriple masayukikurokawa_livedIn_london = new RDFTriple(masayukikurokawa, livedIn, london);
            RDFTriple morphosissantamonicaca_activeIn_moskva = new RDFTriple(morphosissantamonicaca, activeIn, moskva);
            RDFTriple rafaelviñoly_activeIn_newyork = new RDFTriple(rafaelviñoly, activeIn, newyork);
            RDFTriple raimundabraham_livedIn_moskva = new RDFTriple(raimundabraham, livedIn, moskva);
            RDFTriple richardmeier_activeIn_edinburgh = new RDFTriple(richardmeier, activeIn, edinburgh);
            RDFTriple richardmeier_activeIn_london = new RDFTriple(richardmeier, activeIn, london);
            RDFTriple richardmeier_educatedIn_london = new RDFTriple(richardmeier, educatedIn, london);
            RDFTriple santiagocalatrava_livedIn_newyork = new RDFTriple(santiagocalatrava, livedIn, newyork);
            RDFTriple simonungers_livedIn_boston = new RDFTriple(simonungers, livedIn, boston);
            RDFTriple simonungers_livedIn_newyork = new RDFTriple(simonungers, livedIn, newyork);
            RDFTriple tadaoando_activeIn_newyork = new RDFTriple(tadaoando, activeIn, newyork);
            RDFTriple tadaoando_livedIn_northwales = new RDFTriple(tadaoando, livedIn, northwales);
            RDFTriple tadaoando_livedIn_wales = new RDFTriple(tadaoando, livedIn, wales);
            RDFTriple thommayne_activeIn_moskva = new RDFTriple(thommayne, activeIn, moskva);
            RDFTriple thomaskinslow_livedIn_boston = new RDFTriple(thomaskinslow, livedIn, boston);
            RDFTriple thomaskinslow_livedIn_newyork = new RDFTriple(thomaskinslow, livedIn, newyork);
            RDFTriple zahahadid_activeIn_sanfrancisco = new RDFTriple(zahahadid, activeIn, sanfrancisco);

            #endregion

            #region Add triples to graph

            RDFGraph m_graph = new RDFGraph();

            m_graph.AddTriple(aldorossi_activeIn_moskva);
            m_graph.AddTriple(aldorossi_name_aldorossiName);
            m_graph.AddTriple(aldorossi_type_agent);
            m_graph.AddTriple(andrewzago_activeIn_moskva);
            m_graph.AddTriple(andrewzago_name_andrewzagoName);
            m_graph.AddTriple(andrewzago_type_agent);
            m_graph.AddTriple(berlin_name_berlinName);
            m_graph.AddTriple(berlin_type_tgn);
            m_graph.AddTriple(boston_name_bostonName);
            m_graph.AddTriple(boston_type_tgn);
            m_graph.AddTriple(detroit_name_detroitName);
            m_graph.AddTriple(detroit_type_tgn);
            m_graph.AddTriple(edinburgh_name_edinburghName);
            m_graph.AddTriple(edinburgh_type_tgn);
            m_graph.AddTriple(eerosaarinen_activeIn_newyork);
            m_graph.AddTriple(eerosaarinen_name_eerosaarinenName);
            m_graph.AddTriple(eerosaarinen_type_agent);
            m_graph.AddTriple(emilioambasz_activeIn_newyork);
            m_graph.AddTriple(emilioambasz_name_emilioambaszName);
            m_graph.AddTriple(emilioambasz_type_agent);
            m_graph.AddTriple(ernestobrunolapadula_activeIn_newyork);
            m_graph.AddTriple(ernestobrunolapadula_name_ernestobrunolapadulaName);
            m_graph.AddTriple(ernestobrunolapadula_type_agent);
            m_graph.AddTriple(evazeisel_educatedIn_berlin);
            m_graph.AddTriple(evazeisel_name_evazeiselName);
            m_graph.AddTriple(evazeisel_type_agent);
            m_graph.AddTriple(franklloydwright_activeIn_detroit);
            m_graph.AddTriple(franklloydwright_livedIn_moskva);
            m_graph.AddTriple(franklloydwright_name_franklloydwrightName);
            m_graph.AddTriple(franklloydwright_type_agent);
            m_graph.AddTriple(frederickkiesler_livedIn_longbeach);
            m_graph.AddTriple(frederickkiesler_name_frederickkieslerName);
            m_graph.AddTriple(frederickkiesler_type_agent);
            m_graph.AddTriple(fusogomuindcoltdtokyo_livedIn_london);
            m_graph.AddTriple(fusogomuindcoltdtokyo_name_fusogomuindcoltdtokyoName);
            m_graph.AddTriple(fusogomuindcoltdtokyo_type_agent);
            m_graph.AddTriple(giovanniguerrini_activeIn_newyork);
            m_graph.AddTriple(giovanniguerrini_name_giovanniguerriniName);
            m_graph.AddTriple(giovanniguerrini_type_agent);
            m_graph.AddTriple(hallchinacoeastliverpooloh_educatedIn_berlin);
            m_graph.AddTriple(hallchinacoeastliverpooloh_name_hallchinacoeastliverpoolohName);
            m_graph.AddTriple(hallchinacoeastliverpooloh_type_agent);
            m_graph.AddTriple(kiyev_name_kiyevName);
            m_graph.AddTriple(kiyev_type_tgn);
            m_graph.AddTriple(leonkrier_activeIn_newyork);
            m_graph.AddTriple(leonkrier_educatedIn_london);
            m_graph.AddTriple(leonkrier_name_leonkrierName);
            m_graph.AddTriple(leonkrier_type_agent);
            m_graph.AddTriple(london_name_londonName);
            m_graph.AddTriple(london_type_tgn);
            m_graph.AddTriple(longbeach_name_longbeachName);
            m_graph.AddTriple(longbeach_type_tgn);
            m_graph.AddTriple(louisikahn_livedIn_longbeach);
            m_graph.AddTriple(louisikahn_livedIn_newyork);
            m_graph.AddTriple(louisikahn_name_louisikahnName);
            m_graph.AddTriple(louisikahn_type_agent);
            m_graph.AddTriple(ludwigmiesvanderrohe_activeIn_moskva);
            m_graph.AddTriple(ludwigmiesvanderrohe_livedIn_moskva);
            m_graph.AddTriple(ludwigmiesvanderrohe_name_ludwigmiesvanderroheName);
            m_graph.AddTriple(ludwigmiesvanderrohe_type_agent);
            m_graph.AddTriple(mariobotta_activeIn_kiyev);
            m_graph.AddTriple(mariobotta_activeIn_moskva);
            m_graph.AddTriple(mariobotta_livedIn_moskva);
            m_graph.AddTriple(mariobotta_name_mariobottaName);
            m_graph.AddTriple(mariobotta_type_agent);
            m_graph.AddTriple(marioromano_activeIn_newyork);
            m_graph.AddTriple(marioromano_name_marioromanoName);
            m_graph.AddTriple(marioromano_type_agent);
            m_graph.AddTriple(masayukikurokawa_livedIn_london);
            m_graph.AddTriple(masayukikurokawa_name_masayukikurokawaName);
            m_graph.AddTriple(masayukikurokawa_type_agent);
            m_graph.AddTriple(morphosissantamonicaca_activeIn_moskva);
            m_graph.AddTriple(morphosissantamonicaca_name_morphosissantamonicacaName);
            m_graph.AddTriple(morphosissantamonicaca_type_agent);
            m_graph.AddTriple(moskva_name_moskvaName);
            m_graph.AddTriple(moskva_type_tgn);
            m_graph.AddTriple(newyork_name_newyorkName);
            m_graph.AddTriple(newyork_type_tgn);
            m_graph.AddTriple(northwales_name_northwalesName);
            m_graph.AddTriple(northwales_type_tgn);
            m_graph.AddTriple(rafaelviñoly_activeIn_newyork);
            m_graph.AddTriple(rafaelviñoly_name_rafaelviñolyName);
            m_graph.AddTriple(rafaelviñoly_type_agent);
            m_graph.AddTriple(raimundabraham_livedIn_moskva);
            m_graph.AddTriple(raimundabraham_name_raimundabrahamName);
            m_graph.AddTriple(raimundabraham_type_agent);
            m_graph.AddTriple(richardmeier_activeIn_edinburgh);
            m_graph.AddTriple(richardmeier_activeIn_london);
            m_graph.AddTriple(richardmeier_educatedIn_london);
            m_graph.AddTriple(richardmeier_name_richardmeierName);
            m_graph.AddTriple(richardmeier_type_agent);
            m_graph.AddTriple(sanfrancisco_name_sanfranciscoName);
            m_graph.AddTriple(sanfrancisco_type_tgn);
            m_graph.AddTriple(santiagocalatrava_livedIn_newyork);
            m_graph.AddTriple(santiagocalatrava_name_santiagocalatravaName);
            m_graph.AddTriple(santiagocalatrava_type_agent);
            m_graph.AddTriple(simonungers_livedIn_boston);
            m_graph.AddTriple(simonungers_livedIn_newyork);
            m_graph.AddTriple(simonungers_name_simonungersName);
            m_graph.AddTriple(simonungers_type_agent);
            m_graph.AddTriple(tadaoando_activeIn_newyork);
            m_graph.AddTriple(tadaoando_livedIn_northwales);
            m_graph.AddTriple(tadaoando_livedIn_wales);
            m_graph.AddTriple(tadaoando_name_tadaoandoName);
            m_graph.AddTriple(tadaoando_type_agent);
            m_graph.AddTriple(thomaskinslow_livedIn_boston);
            m_graph.AddTriple(thomaskinslow_livedIn_newyork);
            m_graph.AddTriple(thomaskinslow_name_thomaskinslowName);
            m_graph.AddTriple(thomaskinslow_type_agent);
            m_graph.AddTriple(thommayne_activeIn_moskva);
            m_graph.AddTriple(thommayne_name_thommayneName);
            m_graph.AddTriple(thommayne_type_agent);
            m_graph.AddTriple(wales_name_walesName);
            m_graph.AddTriple(wales_type_tgn);
            m_graph.AddTriple(zahahadid_activeIn_sanfrancisco);
            m_graph.AddTriple(zahahadid_name_zahahadidName);
            m_graph.AddTriple(zahahadid_type_agent);

            #endregion

            // Only using RdfXml for this example so no need to write/read all files
            // Write RDF
            RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.RdfXml, m_graph, Server.MapPath("~/").ToString() + "\\" + "tms.rdf");
            //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.Turtle, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.ttl");
            //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.TriX, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.trix");
            //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.NTriples, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.nt");

            // Read RDF
            RDFGraph tmsRDF = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.RdfXml, Server.MapPath("~/").ToString() + "\\tms.rdf");
            //RDFGraph tmsTURTLE = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.Turtle, Environment.CurrentDirectory + "\\tms.ttl");
            //RDFGraph tmsTRIX = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.TriX, Environment.CurrentDirectory + "\\tms.trix");
            //RDFGraph tmsNT = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.NTriples, Environment.CurrentDirectory + "\\tms.nt");

            // Write the RDF into SQL Server.  You have other choices with RDFSharp including RDFMemoryStore

            string m_conn = ConfigurationManager.ConnectionStrings["RDFConnectionString"].ConnectionString;

            RDFSQLServerStore rdf_mssql = new RDFSQLServerStore(m_conn);

            rdf_mssql.MergeGraph(tmsRDF);

            // At this point you can open SQL Server and see a new table called Quadruples with all of the data in the correct format.
            // The first time you run this (successfully), the RdfViewer.aspx page will be empty.
            // Uncomment GetRDF() above and comment LoadRDF() and you should see a datagrid with RDF data.
        }
コード例 #53
0
ファイル: RDFStore.cs プロジェクト: Mozes96/IBH
 /// <summary>
 /// Merges the given graph into the store, avoiding duplicate insertions
 /// </summary>
 public abstract RDFStore MergeGraph(RDFGraph graph);
コード例 #54
0
ファイル: RDFCollection.cs プロジェクト: mdesalvo/RDFSharp
        /// <summary>
        /// Builds the reification graph of the collection
        /// </summary>
        public RDFGraph ReifyCollection()
        {
            RDFGraph reifColl          = new RDFGraph();
            RDFResource reifSubj       = this.ReificationSubject;
            Int32 itemCount            = 0;

            //Manage the empty collection
            if (this.ItemsCount       == 0) {

                //  Subject -> rdf:type  -> rdf:List
                reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.TYPE,  RDFVocabulary.RDF.LIST));

                // Subject  -> rdf:first -> rdf:nil
                reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.FIRST, RDFVocabulary.RDF.NIL));

                // Subject  -> rdf:rest  -> rdf:nil
                reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.REST,  RDFVocabulary.RDF.NIL));

            }

            //Manage the non-empty collection
            else {

                foreach (Object listEnum in this) {

                    //Count the items to keep track of the last one, which will be connected to rdf:nil
                    itemCount++;

                    //  Subject -> rdf:type  -> rdf:List
                    reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.LIST));

                    //  Subject -> rdf:first -> RDFCollection.ITEM[i]
                    if (this.ItemType     == RDFModelEnums.RDFItemTypes.Resource) {
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.FIRST, (RDFResource)listEnum));
                    }
                    else {
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.FIRST, (RDFLiteral)listEnum));
                    }

                    //Not the last one: Subject -> rdf:rest  -> NEWBLANK
                    if (itemCount          < this.ItemsCount) {
                        RDFResource newSub = new RDFResource();
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.REST, newSub));
                        reifSubj           = newSub;
                    }
                    //The last one:     Subject -> rdf:rest  -> rdf:nil
                    else {
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.REST, RDFVocabulary.RDF.NIL));
                    }

                }

            }

            return reifColl;
        }
コード例 #55
0
ファイル: RDFAskQuery.cs プロジェクト: Acidburn0zzz/RDFSharp
        /// <summary>
        /// Applies the query to the given graph 
        /// </summary>
        public RDFAskQueryResult ApplyToGraph(RDFGraph graph) {
            if (graph != null) {
                this.PatternGroupResultTables.Clear();
                this.PatternResultTables.Clear();

                RDFAskQueryResult askResult    = new RDFAskQueryResult();
                if (!this.IsEmpty) {

                    //Iterate the pattern groups of the query
                    foreach (RDFPatternGroup patternGroup in this.PatternGroups) {

                        //Step 1: Get the intermediate result tables of the current pattern group
                        RDFAskQueryEngine.EvaluatePatterns(this, patternGroup, graph);

                        //Step 2: Get the result table of the current pattern group
                        RDFAskQueryEngine.CombinePatterns(this, patternGroup);

                        //Step 3: Apply the filters of the current pattern group to its result table
                        RDFAskQueryEngine.ApplyFilters(this, patternGroup);

                    }

                    //Step 4: Get the result table of the query
                    DataTable queryResultTable = RDFQueryEngine.CombineTables(this.PatternGroupResultTables.Values.ToList<DataTable>(), false);

                    //Step 5: Transform the result into a boolean response 
                    askResult.AskResult        = (queryResultTable.Rows.Count > 0);

                }

                return askResult;
            }
            throw new RDFQueryException("Cannot execute ASK query because given \"graph\" parameter is null.");
        }
コード例 #56
0
        /// <summary>
        /// Emits a graph containing the ontology triples describing this ontology resource
        /// </summary>
        public virtual RDFGraph ToRDFGraph() {
            var result   = new RDFGraph();

            //THIS -> owl:versionInfo  -> THIS.VERSIONINFO[i]
            var verInfos = this.VersionInfoEnumerator();
            while (verInfos.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.OWL.VERSION_INFO, (RDFLiteral)verInfos.Current.Value));
            }

            //THIS -> rdfs:comment     -> THIS.COMMENT[i]
            var comments = this.CommentEnumerator();
            while (comments.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.COMMENT, (RDFLiteral)comments.Current.Value));
            }

            //THIS -> rdfs:label       -> THIS.LABEL[i]
            var labels   = this.LabelEnumerator();
            while (labels.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.LABEL, (RDFLiteral)labels.Current.Value));
            }

            //THIS -> rdfs:seeAlso     -> THIS.SEEALSO[i]
            var seeAlso  = this.SeeAlsoEnumerator();
            while (seeAlso.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.SEE_ALSO, (RDFResource)seeAlso.Current.Value));
            }

            //THIS -> rdfs:isDefinedBy -> THIS.ISDEFINEDBY[i]
            var isDefBy  = this.IsDefinedByEnumerator();
            while (isDefBy.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.IS_DEFINED_BY, (RDFResource)isDefBy.Current.Value));
            }

            //THIS -> THIS.CUSTOMANNOTATION[i].PROPERTY -> THIS.CUSTOMANNOTATION[i].FACT
            var custAnn  = this.CustomAnnotationsEnumerator();
            while (custAnn.MoveNext()) {
                if (custAnn.Current.AttributeValue.IsObjectFact()) {
                    result.AddTriple(new RDFTriple((RDFResource)this.Value, (RDFResource)custAnn.Current.AttributeProperty.Value, (RDFResource)custAnn.Current.AttributeValue.Value));
                }
                else {
                    result.AddTriple(new RDFTriple((RDFResource)this.Value, (RDFResource)custAnn.Current.AttributeProperty.Value, (RDFLiteral)custAnn.Current.AttributeValue.Value));
                }
            }

            return result;
        }
コード例 #57
0
ファイル: RDFTriX.cs プロジェクト: mdesalvo/RDFSharp
        /// <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.Ignore;
                        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);
            }
        }
コード例 #58
0
ファイル: RDFXml.cs プロジェクト: Acidburn0zzz/RDFSharp
        /// <summary>
        /// Serializes the given graph to the given filepath using Xml data format. 
        /// </summary>
        internal static void Serialize(RDFGraph graph, String filepath) {
            try {

                #region serialize
                using (XmlTextWriter rdfxmlWriter = new XmlTextWriter(filepath, Encoding.UTF8))  {
                    XmlDocument rdfDoc            = new XmlDocument();
                    rdfxmlWriter.Formatting       = Formatting.Indented;

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

                    #region rdfRoot
                    XmlNode rdfRoot               = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":RDF", RDFVocabulary.RDF.BASE_URI);
                    XmlAttribute rdfRootNS        = rdfDoc.CreateAttribute("xmlns:" + RDFVocabulary.RDF.PREFIX);
                    XmlText rdfRootNSText         = rdfDoc.CreateTextNode(RDFVocabulary.RDF.BASE_URI);
                    rdfRootNS.AppendChild(rdfRootNSText);
                    rdfRoot.Attributes.Append(rdfRootNS);

                    #region prefixes
                    //Write the graph's prefixes (except for "rdf", which has already been written)
                    graph.GraphMetadata.Namespaces.ForEach(p => {
                        if (!p.Prefix.Equals(RDFVocabulary.RDF.PREFIX, StringComparison.Ordinal) && !p.Prefix.Equals("base", StringComparison.Ordinal)) {
                            XmlAttribute pfRootNS     = rdfDoc.CreateAttribute("xmlns:" + p.Prefix);
                            XmlText pfRootNSText      = rdfDoc.CreateTextNode(p.ToString());
                            pfRootNS.AppendChild(pfRootNSText);
                            rdfRoot.Attributes.Append(pfRootNS);
                        }
                    });
                    //Write the graph's base uri to resolve eventual relative #IDs
                    XmlAttribute pfBaseNS             = rdfDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":base");
                    XmlText pfBaseNSText              = rdfDoc.CreateTextNode(graph.Context.ToString());
                    pfBaseNS.AppendChild(pfBaseNSText);
                    rdfRoot.Attributes.Append(pfBaseNS);
                    #endregion

                    #region linq
                    //Group the graph's triples by subj
                    var groupedList =  (from    triple in graph
                                        orderby triple.Subject.ToString()
                                        group   triple by new {
                                            subj = triple.Subject.ToString()
                                        });
                    #endregion

                    #region graph
                    //Iterate over the calculated groups
                    Dictionary<RDFResource, XmlNode> containers = new Dictionary<RDFResource, XmlNode>();
                    
                    //Floating containers have reification subject which is never object of any graph's triple
                    Boolean floatingContainers                  = graph.GraphMetadata.Containers.Keys.Any(k =>
                                                                        graph.Triples.Values.Count(v => v.Object.Equals(k)) == 0);
                    //Floating collections have reification subject which is never object of any graph's triple
                    Boolean floatingCollections                 = graph.GraphMetadata.Collections.Keys.Any(k => 
                                                                        graph.Triples.Values.Count(v => v.Object.Equals(k)) == 0);

                    foreach (var group in groupedList) {

                        #region subj
                        //Check if the current subj is a container or a collection subj: if so it must be
                        //serialized in the canonical RDF/XML way instead of the "rdf:Description" way
                        XmlNode subjNode              = null;
                        String subj                   = group.Key.subj;

                        //It is a container subj, so add it to the containers pool
                        if (graph.GraphMetadata.Containers.Keys.Any(k => k.ToString().Equals(subj, StringComparison.Ordinal)) && !floatingContainers) {
                            switch (graph.GraphMetadata.Containers.Single(c => c.Key.ToString().Equals(subj, StringComparison.Ordinal)).Value) {
                                case RDFModelEnums.RDFContainerTypes.Bag:
                                    subjNode  = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Bag", RDFVocabulary.RDF.BASE_URI);
                                    containers.Add(new RDFResource(subj), subjNode);
                                    break;
                                case RDFModelEnums.RDFContainerTypes.Seq:
                                    subjNode  = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Seq", RDFVocabulary.RDF.BASE_URI);
                                    containers.Add(new RDFResource(subj), subjNode);
                                    break;
                                case RDFModelEnums.RDFContainerTypes.Alt:
                                    subjNode  = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Alt", RDFVocabulary.RDF.BASE_URI);
                                    containers.Add(new RDFResource(subj), subjNode);
                                    break;
                            }
                        }

                        //It is a subj of a collection of resources, so do not append triples having it as a subject
                        //because we will reconstruct the collection and append it as a whole
                        else if (graph.GraphMetadata.Collections.Keys.Any(k => k.ToString().Equals(subj, StringComparison.Ordinal))                                                         &&
                                 graph.GraphMetadata.Collections.Single(c => c.Key.ToString().Equals(subj, StringComparison.Ordinal)).Value.ItemType == RDFModelEnums.RDFItemTypes.Resource &&
                                 !floatingCollections) {
                            continue;
                        }

                        //It is neither a container or a collection subj
                        else {
                            subjNode                       = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Description", RDFVocabulary.RDF.BASE_URI);
                            //<rdf:Description rdf:nodeID="blankID">
                            XmlAttribute subjNodeDesc      = null;
                            XmlText subjNodeDescText       = rdfDoc.CreateTextNode(group.Key.subj);
                            if (group.Key.subj.StartsWith("bnode:")) {
                                subjNodeDescText.InnerText = subjNodeDescText.InnerText.Replace("bnode:", String.Empty);
                                subjNodeDesc               = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":nodeID", RDFVocabulary.RDF.BASE_URI);
                            }
                            //<rdf:Description rdf:about="subjURI">
                            else {
                                subjNodeDesc               = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":about", RDFVocabulary.RDF.BASE_URI);
                            }
                            subjNodeDesc.AppendChild(subjNodeDescText);
                            subjNode.Attributes.Append(subjNodeDesc);
                        }
                        #endregion

                        #region predObjList
                        //Iterate over the triples of the current group
                        foreach (var triple in group) {

                            //Do not append the triple if it is "SUBJECT rdf:type rdf:[Bag|Seq|Alt]" 
                            if (!(triple.Predicate.Equals(RDFVocabulary.RDF.TYPE) &&
                                  (subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal) ||
                                   subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) ||
                                   subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal)))) {

                                #region pred
                                String predString     = triple.Predicate.ToString();
                                //"<predPREF:predURI"
                                RDFNamespace predNS   = 
								    (RDFNamespaceRegister.GetByNamespace(predString) ?? 
									     RDFModelUtilities.GenerateNamespace(predString, false));
                                //Refine the pred with eventually necessary sanitizations
                                String predUri        = predString.Replace(predNS.ToString(), predNS.Prefix + ":")
                                                                  .Replace(":#", ":")
                                                                  .TrimEnd(new Char[] { ':', '/' });
                                //Sanitize eventually detected automatic namespace
                                if (predUri.StartsWith("autoNS:")) {
                                    predUri           = predUri.Replace("autoNS:", string.Empty);
                                }
                                //Do not write "xmlns" attribute if the predUri is the context of the graph
                                XmlNode predNode      = null;
                                if (predNS.ToString().Equals(graph.Context.ToString(), StringComparison.Ordinal)) {
                                    predNode          = rdfDoc.CreateNode(XmlNodeType.Element, predUri, null);
                                }
                                else {
                                    predNode          = rdfDoc.CreateNode(XmlNodeType.Element, predUri, predNS.ToString());
                                }
                                #endregion

                                #region object
                                if (triple.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO) {

                                    //If the object is a container subj, we must append its entire node saved in the containers dictionary
                                    if (containers.Keys.Any(k => k.Equals(triple.Object)) && !floatingContainers) {
                                        predNode.AppendChild(containers.Single(c => c.Key.Equals(triple.Object)).Value);
                                    }

                                    //Else, if the object is a subject of a collection of resources, we must append the "rdf:parseType=Collection" attribute to the predicate node
                                    else if (graph.GraphMetadata.Collections.Keys.Any(k => k.Equals(triple.Object))                                                                                     &&
                                             graph.GraphMetadata.Collections.Single(c => c.Key.Equals(triple.Object)).Value.ItemType == RDFModelEnums.RDFItemTypes.Resource &&
                                             !floatingCollections) {
                                        XmlAttribute rdfParseType = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":parseType", RDFVocabulary.RDF.BASE_URI);
                                        XmlText rdfParseTypeText  = rdfDoc.CreateTextNode("Collection");
                                        rdfParseType.AppendChild(rdfParseTypeText);
                                        predNode.Attributes.Append(rdfParseType);
                                        //Then we append sequentially the collection elements 
                                        List<XmlNode> collElements = RDFModelUtilities.ReconstructCollection(graph.GraphMetadata, (RDFResource)triple.Object, rdfDoc);
                                        collElements.ForEach(c => predNode.AppendChild(c)); 
                                    }

                                    //Else, threat it as a traditional object node
                                    else {
                                        String objString               = triple.Object.ToString();
                                        XmlAttribute predNodeDesc      = null;
                                        XmlText predNodeDescText       = rdfDoc.CreateTextNode(objString);
                                        //  rdf:nodeID="blankID">
                                        if (objString.StartsWith("bnode:")) {
                                            predNodeDescText.InnerText = predNodeDescText.InnerText.Replace("bnode:", String.Empty);  
                                            predNodeDesc               = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":nodeID", RDFVocabulary.RDF.BASE_URI);
                                        }
                                        //  rdf:resource="objURI">
                                        else {
                                            predNodeDesc               = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":resource", RDFVocabulary.RDF.BASE_URI);
                                        }
                                        predNodeDesc.AppendChild(predNodeDescText);
                                        predNode.Attributes.Append(predNodeDesc);
                                    }
                                }
                                #endregion

                                #region literal
                                else {

                                    #region plain literal
                                    if (triple.Object is RDFPlainLiteral) {
                                        RDFPlainLiteral pLit      = (RDFPlainLiteral)triple.Object;
                                        //  xml:lang="plitLANG">
                                        if (pLit.Language        != String.Empty) {
                                            XmlAttribute plainLiteralLangNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI);
                                            XmlText plainLiteralLangNodeDescText  = rdfDoc.CreateTextNode(pLit.Language);
                                            plainLiteralLangNodeDesc.AppendChild(plainLiteralLangNodeDescText);
                                            predNode.Attributes.Append(plainLiteralLangNodeDesc);
                                        }
                                    }
                                    #endregion

                                    #region typed literal
                                    //  rdf:datatype="tlitURI">
                                    else {
                                        RDFTypedLiteral tLit      = (RDFTypedLiteral)triple.Object;
                                        XmlAttribute typedLiteralNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":datatype", RDFVocabulary.RDF.BASE_URI);
                                        XmlText typedLiteralNodeDescText  = rdfDoc.CreateTextNode(tLit.Datatype.ToString());
                                        typedLiteralNodeDesc.AppendChild(typedLiteralNodeDescText);
                                        predNode.Attributes.Append(typedLiteralNodeDesc);
                                    }
                                    #endregion

                                    //litVALUE</predPREF:predURI>"
                                    XmlText litNodeDescText       = rdfDoc.CreateTextNode(((RDFLiteral)triple.Object).Value);
                                    predNode.AppendChild(litNodeDescText);
                                }
                                #endregion

                                subjNode.AppendChild(predNode);
                            }

                        }

                        //Raw containers must not be written as-is, instead they have to be saved
                        //and attached when their subj is found later as object of a triple
                        if (!subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal) &&
                            !subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) &&
                            !subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal)) {
                            rdfRoot.AppendChild(subjNode);
                        }
                        #endregion

                    }
                    #endregion

                    rdfDoc.AppendChild(rdfRoot);
                    #endregion

                    rdfDoc.Save(rdfxmlWriter);
                }
                #endregion

            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot serialize Xml because: " + ex.Message, ex);
            }
        }
コード例 #59
0
        /// <summary>
        /// Deserializes the given TriX filepath to a graph. 
        /// </summary>
        internal static RDFGraph Deserialize(String filepath) {
            try {

                #region deserialize
                XmlReaderSettings xrs       = new XmlReaderSettings();
                xrs.IgnoreComments          = true;
                xrs.DtdProcessing           = DtdProcessing.Ignore;

                RDFGraph result             = new RDFGraph();
                using(XmlReader xr          = XmlReader.Create(new StreamReader(filepath, Encoding.UTF8), xrs)) {                    

                    #region load
                    XmlDocument trixDoc     = new XmlDocument();
                    trixDoc.Load(xr);
                    #endregion

                    #region graph
                    if (trixDoc.DocumentElement != null) {
                        var graphEnum                   = trixDoc.DocumentElement.ChildNodes.GetEnumerator();
                        while (graphEnum != null       && graphEnum.MoveNext()) {
                            XmlNode  graph              = (XmlNode)graphEnum.Current;
                            RDFGraph g                  = new RDFGraph();

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

                                #region uri
                                if (triple.Name.Equals("uri", StringComparison.Ordinal)) {
                                    g.Context           = 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 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 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);
                                            }
                                        }
                                        g.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
                                                g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                            new RDFResource(triple.ChildNodes[1].InnerText),
                                                                            new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText), xmlLang.Value)));

                                            }
                                            else {

                                                //Plain literal without language
                                                g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                        new RDFResource(triple.ChildNodes[1].InnerText),
                                                                        new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText))));

                                            }
                                        }
                                        else {

                                            //Plain literal without language
                                            g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                        new RDFResource(triple.ChildNodes[1].InnerText),
                                                                        new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText))));

                                        }
                                    }
                                    #endregion

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

                                    #endregion

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

                                }
                                #endregion

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

                            }
                            #endregion

                            result                      = result.UnionWith(g);
                            result.Context              = g.Context;
                        }
                    }
                    #endregion

                }
                return result;
                #endregion

            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize TriX because: " + ex.Message);
            }
        }
コード例 #60
0
        /// <summary>
        /// Applies the query to the given graph 
        /// </summary>
        public RDFDescribeQueryResult ApplyToGraph(RDFGraph graph) {
            if (graph != null) {
                this.PatternGroupResultTables.Clear();
                this.PatternResultTables.Clear();

                RDFDescribeQueryResult describeResult  = new RDFDescribeQueryResult(this.ToString());
                if (!this.IsEmpty) {

                    //Iterate the pattern groups of the query
                    foreach (RDFPatternGroup patternGroup in this.PatternGroups) {

                        //Step 1: Get the intermediate result tables of the current pattern group
                        RDFDescribeQueryEngine.EvaluatePatterns(this, patternGroup, graph);

                        //Step 2: Get the result table of the current pattern group
                        RDFDescribeQueryEngine.CombinePatterns(this, patternGroup);

                        //Step 3: Apply the filters of the current pattern group to its result table
                        RDFDescribeQueryEngine.ApplyFilters(this, patternGroup);

                    }

                    //Step 4: Get the result table of the query
                    DataTable queryResultTable         = RDFQueryEngine.CombineTables(this.PatternGroupResultTables.Values.ToList<DataTable>(), false);

                    //Step 5: Describe the terms from the result table
                    DataTable describeResultTable      = RDFDescribeQueryEngine.DescribeTerms(this, graph, queryResultTable);

                    //Step 6: Apply the modifiers of the query to the result table
                    describeResult.DescribeResults     = RDFDescribeQueryEngine.ApplyModifiers(this, describeResultTable);

                }
                else {

                    //In this case the only chance to proceed is to have resources in the describe terms,
                    //which will be used to search for S-P-O data. Variables are omitted in this scenario.
                    if (this.DescribeTerms.Any(dt => dt is RDFResource)) {

                        //Step 1: Describe the terms from the result table
                        DataTable describeResultTable  = RDFDescribeQueryEngine.DescribeTerms(this, graph, new DataTable());

                        //Step 2: Apply the modifiers of the query to the result table
                        describeResult.DescribeResults = RDFDescribeQueryEngine.ApplyModifiers(this, describeResultTable);

                    }

                }

                return describeResult;
            }
            throw new RDFQueryException("Cannot execute DESCRIBE query because given \"graph\" parameter is null.");
        }