コード例 #1
0
        public static IGraph Load(XDocument nuspec, string baseAddress)
        {
            string path = @"..\..\..\..\..\src\MakeMetadata\MakeMetadata\nuspec2package.xslt";

            XslCompiledTransform transform = CreateTransform(path);

            XsltArgumentList arguments = new XsltArgumentList();

            arguments.AddParam("base", "", baseAddress);

            XDocument rdfxml = new XDocument();

            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                transform.Transform(nuspec.CreateReader(), arguments, writer);
            }

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            XmlDocument  doc          = new XmlDocument();

            doc.Load(rdfxml.CreateReader());
            IGraph graph = new Graph();

            rdfXmlParser.Load(graph, doc);

            return(graph);
        }
コード例 #2
0
        public static IGraph GraphFromXml(XDocument original, XslCompiledTransform transform, XsltArgumentList arguments)
        {
            XDocument rdfxml = new XDocument();

            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                transform.Transform(original.CreateReader(), arguments, writer);
            }

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            XmlDocument  doc          = new XmlDocument();

            doc.Load(rdfxml.CreateReader());

            //DEBUG
            //using (var xmlWriter = XmlWriter.Create(Console.Out))
            //{
            //    doc.WriteTo(xmlWriter);
            //}

            IGraph graph = new Graph();

            rdfXmlParser.Load(graph, doc);

            return(graph);
        }
コード例 #3
0
        private void LoadInGraph(String path)
        {
            RdfXmlParser ttlparser = new RdfXmlParser();

            try
            {
                ttlparser.Load(situation, path);
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                logger.LogFunction("Parser Error");
                logger.LogFunction(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                logger.LogFunction("RDF Error");
                logger.LogFunction(rdfEx.Message);
            }
            catch (Exception ex)
            {
                logger.LogFunction("Unknown Error");
                logger.LogFunction(ex.Message);
            }
        }
コード例 #4
0
        public void ParsingBaseUriAssignmentRdfXml()
        {
            Graph g = new Graph();

            g.BaseUri = new Uri("http://example.org/RdfXml");

            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            RdfXmlWriter           writer    = new RdfXmlWriter();

            writer.Save(g, strWriter);

            Console.WriteLine("Original Base URI: " + ShowBaseUri(g.BaseUri));

            Console.WriteLine("Output using RdfXmlWriter:");
            Console.WriteLine(strWriter.ToString());
            Console.WriteLine();

            Graph        h      = new Graph();
            RdfXmlParser parser = new RdfXmlParser();

            parser.Load(h, new System.IO.StringReader(strWriter.ToString()));

            Console.WriteLine("Base URI after round-trip using RdfXmlWriter: " + ShowBaseUri(h.BaseUri));
            Assert.IsNotNull(h.BaseUri, "Base URI should not be null");
        }
コード例 #5
0
        public void ReadRDL(string fileName)
        {
            IGraph g = new Graph();

            //IUriNode dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            //IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            //ILiteralNode helloWorld = g.CreateLiteralNode("Hello World");
            //ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");

            //g.Assert(new Triple(dotNetRDF, says, helloWorld));
            //g.Assert(new Triple(dotNetRDF, says, bonjourMonde));

            //foreach (Triple t in g.Triples)
            //{
            //    Console.WriteLine(t.ToString());
            //}

            //NTriplesWriter ntwriter = new NTriplesWriter();
            //ntwriter.Save(g, "HelloWorld.nt");

            //RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();
            //rdfxmlwriter.Save(g, "HelloWorld.rdf");

            RdfXmlParser fileParser = new RdfXmlParser();

            fileParser.Load(g, fileName);

            //VDS.RDF.Nam
        }
コード例 #6
0
        private void ProcessRootServices()
        {
            try {
                OslcClient          rootServicesClient = new OslcClient();
                HttpResponseMessage response           = rootServicesClient.GetResource(rootServicesUrl, OSLCConstants.CT_RDF);
                Stream       stream       = response.Content.ReadAsStreamAsync().Result;
                IGraph       rdfGraph     = new Graph();
                IRdfReader   parser       = new RdfXmlParser();
                StreamReader streamReader = new StreamReader(stream);

                using (streamReader)
                {
                    parser.Load(rdfGraph, streamReader);

                    //get the catalog URL
                    catalogUrl = GetRootServicesProperty(rdfGraph, catalogNamespace, catalogProperty);

                    //get the OAuth URLs
                    requestTokenUrl       = GetRootServicesProperty(rdfGraph, JFS_NAMESPACE, JazzRootServicesConstants.OAUTH_REQUEST_TOKEN_URL);
                    authorizationTokenUrl = GetRootServicesProperty(rdfGraph, JFS_NAMESPACE, JazzRootServicesConstants.OAUTH_USER_AUTH_URL);
                    accessTokenUrl        = GetRootServicesProperty(rdfGraph, JFS_NAMESPACE, JazzRootServicesConstants.OAUTH_ACCESS_TOKEN_URL);
                    try {             // Following field is optional, try to get it, if not found ignore exception because it will use the default
                        authorizationRealm = GetRootServicesProperty(rdfGraph, JFS_NAMESPACE, JazzRootServicesConstants.OAUTH_REALM_NAME);
                    } catch (ResourceNotFoundException e) {
                        // Ignore
                    }
                }
            } catch (Exception e) {
                throw new RootServicesException(baseUrl, e);
            }
        }
コード例 #7
0
ファイル: RdfXmlTests.cs プロジェクト: yuryk53/dotnetrdf
        public void ParsingRdfXmlEmptyStrings()
        {
            NTriplesFormatter formatter = new NTriplesFormatter();
            RdfXmlParser      domParser = new RdfXmlParser(RdfXmlParserMode.DOM);
            Graph             g         = new Graph();

            domParser.Load(g, "resources\\empty-string-rdfxml.rdf");

            Console.WriteLine("DOM Parser parsed OK");

            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString(formatter));
            }
            Console.WriteLine();

            RdfXmlParser streamingParser = new RdfXmlParser(RdfXmlParserMode.Streaming);
            Graph        h = new Graph();

            streamingParser.Load(h, "resources\\empty-string-rdfxml.rdf");

            Console.WriteLine("Streaming Parser parsed OK");

            foreach (Triple t in h.Triples)
            {
                Console.WriteLine(t.ToString(formatter));
            }

            Assert.AreEqual(g, h, "Graphs should be equal");
        }
コード例 #8
0
        static IGraph CreateNuspecGraph(XDocument nuspec, Uri baseAddress, XslCompiledTransform xslt)
        {
            XsltArgumentList arguments = new XsltArgumentList();

            arguments.AddParam("base", "", baseAddress.ToString());
            arguments.AddParam("extension", "", ".json");

            arguments.AddExtensionObject("urn:helper", new XsltHelper());

            XDocument rdfxml = new XDocument();

            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                xslt.Transform(nuspec.CreateReader(), arguments, writer);
            }

            XmlDocument doc = new XmlDocument();

            doc.Load(rdfxml.CreateReader());

            IGraph       graph        = new Graph();
            RdfXmlParser rdfXmlParser = new RdfXmlParser();

            rdfXmlParser.Load(graph, doc);

            return(graph);
        }
コード例 #9
0
        public static IGraph CreateNuspecGraph(XDocument nuspec, string baseAddress)
        {
            nuspec = NormalizeNuspecNamespace(nuspec);

            XslCompiledTransform transform = CreateTransform("xslt.nuspec.xslt");

            XsltArgumentList arguments = new XsltArgumentList();

            arguments.AddParam("base", "", baseAddress + "packages/");
            arguments.AddParam("extension", "", ".json");

            arguments.AddExtensionObject("urn:helper", new XsltHelper());

            XDocument rdfxml = new XDocument();

            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                transform.Transform(nuspec.CreateReader(), arguments, writer);
            }

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            XmlDocument  doc          = new XmlDocument();

            doc.Load(rdfxml.CreateReader());
            IGraph graph = new Graph();

            rdfXmlParser.Load(graph, doc);

            return(graph);
        }
        private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = Environment.CurrentDirectory;
                ofd.Filter           = "RDF Files (*.rdf)|*.rdf|Turtle Files (*.ttl)|*.ttl|All Files (*.*)|*.*";
                if (ofd.ShowDialog().Value)
                {
                    string filePath = ofd.FileName;

                    switch (ModeComboBox.SelectedIndex)
                    {
                    case 0:     // RDF/XML
                        RdfXmlParser rdfXmlParser = new RdfXmlParser(RdfXmlParserMode.Streaming);
                        myGraph = new Graph();
                        rdfXmlParser.Load(myGraph, filePath);
                        break;

                    case 1:     // NTriples
                        NTriplesParser ntp = new NTriplesParser();
                        myGraph = new Graph();
                        ntp.Load(myGraph, filePath);
                        break;
                    }

                    MessageBox.Show("Graph Loaded From File Successfully", "Connected", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "ERROR", MessageBoxButton.OK);
            }
        }
コード例 #11
0
ファイル: RdfXmlTests.cs プロジェクト: yuryk53/dotnetrdf
        public void ParsingRdfXmlWithUrlEscapedNodes2()
        {
            //Originally submitted by Rob Styles as part of CORE-251, modified somewhat during debugging process
            NTriplesFormatter formatter = new NTriplesFormatter();
            RdfXmlParser      domParser = new RdfXmlParser(RdfXmlParserMode.DOM);
            Graph             g         = new Graph();

            domParser.Load(g, "resources\\urlencodes-in-rdfxml.rdf");

            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString(formatter));
            }

            Uri encoded   = new Uri("http://example.com/some%20encoded%2FUri");
            Uri unencoded = new Uri("http://example.com/some encoded/Uri");

            Assert.IsTrue(EqualityHelper.AreUrisEqual(encoded, unencoded), "URIs should be equivalent");

            IUriNode encodedNode = g.GetUriNode(encoded);

            Assert.IsNotNull(encodedNode, "The encoded node should be returned by its encoded URI");
            IUriNode unencodedNode = g.GetUriNode(unencoded);

            Assert.IsNotNull(unencodedNode, "The unencoded node should be returned by its unencoded URI");

            IUriNode pred = g.CreateUriNode(new Uri("http://example.org/schema/encoded"));

            Assert.IsTrue(g.ContainsTriple(new Triple(encodedNode, pred, g.CreateLiteralNode("true"))), "The encoded node should have the property 'true' from the file");
            Assert.IsTrue(g.ContainsTriple(new Triple(unencodedNode, pred, g.CreateLiteralNode("false"))), "The unencoded node should have the property 'false' from the file");
        }
コード例 #12
0
        public static IGraph GetDocument(string transformName, IDictionary <string, string> transformArgs, XDocument data, string baseAddress)
        {
            XslCompiledTransform transform = CreateTransform(transformName);

            XsltArgumentList arguments = new XsltArgumentList();

            arguments.AddParam("base", "", baseAddress);
            foreach (KeyValuePair <string, string> arg in transformArgs)
            {
                arguments.AddParam(arg.Key, "", arg.Value);
            }

            XDocument rdfxml = new XDocument();

            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                transform.Transform(data.CreateReader(), arguments, writer);
            }

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            XmlDocument  doc          = new XmlDocument();

            doc.Load(rdfxml.CreateReader());
            IGraph graph = new Graph();

            rdfXmlParser.Load(graph, doc);

            return(graph);
        }
コード例 #13
0
        public IEnumerable <IDataObject> BindRdfDataObjects(XDocument rdfXmlDocument,
                                                            IList <OrderingDirection> orderingDirections)
        {
            var g = new Graph();

#if PORTABLE || WINDOWS_PHONE
            var parser = new RdfXmlParser(RdfXmlParserMode.Streaming);
            // This is pretty nasty, having to deserialize only to go through parsing again
            parser.Load(g, new System.IO.StringReader(rdfXmlDocument.ToString()));
#else
            var parser = new RdfXmlParser(RdfXmlParserMode.DOM);
            parser.Load(g, rdfXmlDocument.AsXmlDocument());
#endif
            var p              = new VDS.RDF.Query.LeviathanQueryProcessor(new InMemoryDataset(g));
            var queryString    = MakeOrderedResourceQuery(orderingDirections);
            var sparqlParser   = new SparqlQueryParser();
            var query          = sparqlParser.ParseFromString(queryString);
            var queryResultSet = p.ProcessQuery(query) as VDS.RDF.Query.SparqlResultSet;
            foreach (var row in queryResultSet.Results)
            {
                INode uriNode;
                if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode)
                {
                    yield return(BindRdfDataObject(uriNode as IUriNode, g));
                }
            }
        }
コード例 #14
0
ファイル: RelativeUriTests.cs プロジェクト: yuryk53/dotnetrdf
        public void ParsingRelativeUriAppBaseRdfXml2()
        {
            //This invocation succeeds because when invoking because
            //we manually set the Base URI prior to invoking the parser

            Graph g = new Graph();

            g.BaseUri = new Uri("http://example.org");
            RdfXmlParser parser = new RdfXmlParser();

            parser.Load(g, "resources\\rdfxml-relative-uri.rdf");

            //Expect a non-empty grpah with a single triple
            Assert.IsFalse(g.IsEmpty);
            Assert.AreEqual(1, g.Triples.Count);
            Triple t = g.Triples.First();

            //Object should get it's relative URI resolved into
            //the correct HTTP URI
            Uri obj = ((IUriNode)t.Object).Uri;

            Assert.AreEqual("http", obj.Scheme);
            Assert.AreEqual("example.org", obj.Host);
            Assert.AreEqual("relative", obj.Segments[1]);
        }
コード例 #15
0
        public void LoadFromFile(string filePath, DatasourceFileType fileType)
        {
            try
            {
                switch (fileType)
                {
                case DatasourceFileType.Rdfxml:     // RDF/XML
                    RdfXmlParser rdfXmlParser = new RdfXmlParser(RdfXmlParserMode.Streaming);
                    myGraph = new Graph();
                    rdfXmlParser.Load(myGraph, filePath);
                    break;

                case DatasourceFileType.NTriples:     // NTriples
                    NTriplesParser ntp = new NTriplesParser();
                    myGraph = new Graph();
                    ntp.Load(myGraph, filePath);
                    break;
                }
            }
            catch (Exception ex)
            {
                MySoapFault fault = new MySoapFault();
                fault.Operation   = "LoadFromFile";
                fault.Reason      = "Error in loading datasource file into graph .";
                fault.Details     = ex.Message;
                fault.MoreDetails = ex.StackTrace;
                throw new FaultException <MySoapFault>(fault);
            }
        }
コード例 #16
0
ファイル: Utils.cs プロジェクト: gep13/NuGet.Jobs
        public static IGraph CreateNuspecGraph(XDocument nuspec, string baseAddress, bool normalizeXml = false)
        {
            XsltArgumentList arguments = new XsltArgumentList();

            arguments.AddParam("base", "", baseAddress);
            arguments.AddParam("extension", "", ".json");

            arguments.AddExtensionObject("urn:helper", new XsltHelper());

            nuspec = SafeXmlTransform(nuspec.CreateReader(), XslTransformNormalizeNuSpecNamespaceCache.Value);
            var rdfxml = SafeXmlTransform(nuspec.CreateReader(), XslTransformNuSpecCache.Value, arguments);

            var doc = SafeCreateXmlDocument(rdfxml.CreateReader());

            if (normalizeXml)
            {
                NormalizeXml(doc);
            }

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            IGraph       graph        = new Graph();

            rdfXmlParser.Load(graph, doc);

            return(graph);
        }
コード例 #17
0
        // Load RDF content from xml file
        public static Graph LoadFromFileXml(String fileName)
        {
            Graph        g         = new Graph();
            RdfXmlParser xmlParser = new RdfXmlParser();

            xmlParser.Load(g, fileName);
            return(g);
        }
コード例 #18
0
        public static Pubmed LoadFromXML(string filename)
        {
            RdfXmlParser xmlParser = new RdfXmlParser();
            IGraph       g         = new Graph();

            xmlParser.Load(g, filename);

            return(new Pubmed(g));
        }
コード例 #19
0
        public Response Refresh(string graphName, XDocument xDocument)
        {
            Response response = new Response();

            response.StatusList = new List <Status>();

            Status status = new Status();

            status.Messages = new Messages();

            try
            {
                status.Identifier = graphName;

                DateTime startTime = DateTime.Now;
                _graphMap = _mapping.FindGraphMap(graphName);

                // create xdoc from rdf xelement
                Uri         graphUri    = new Uri(_graphNs.NamespaceName + graphName);
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xDocument.ToString());
                xDocument.Root.RemoveAll();

                // load xdoc to graph
                RdfXmlParser parser = new RdfXmlParser();
                _graph.Clear();
                _graph.BaseUri = graphUri;
                parser.Load(_graph, xmlDocument);
                xmlDocument.RemoveAll();

                // delete old graph and save new one
                DeleteGraph(graphUri);
                _tripleStore.SaveGraph(_graph);

                DateTime endTime  = DateTime.Now;
                TimeSpan duration = endTime.Subtract(startTime);

                status.Messages.Add("Graph [" + graphName + "] has been refreshed in triple store successfully.");
                status.Messages.Add(
                    String.Format("Execution time [{0}:{1}.{2}] minutes.",
                                  duration.Minutes,
                                  duration.Seconds,
                                  duration.Milliseconds
                                  )
                    );
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Error refreshing graph [{0}]. {1}", graphName, ex));

                status.Level = StatusLevel.Error;
                status.Messages.Add(String.Format("Error refreshing graph [{0}]. {1}", graphName, ex));
            }

            response.Append(status);
            return(response);
        }
コード例 #20
0
ファイル: RelativeUriTests.cs プロジェクト: yuryk53/dotnetrdf
        public void ParsingRelativeUriNoBaseRdfXml()
        {
            //This invocation fails because when invoking the parser directly
            //the Base URI is not set to the file URI

            Graph        g      = new Graph();
            RdfXmlParser parser = new RdfXmlParser();

            parser.Load(g, "resources\\rdfxml-relative-uri.rdf");
        }
コード例 #21
0
        public void ParsingRdfXmlStackOverflow1()
        {
            IGraph       g      = new Graph();
            RdfXmlParser parser = new RdfXmlParser();

            parser.Load(g, @"resources\cogapp.rdf");

            Assert.False(g.IsEmpty);
            Assert.Equal(9358, g.Triples.Count);
        }
コード例 #22
0
        public void ParsingRdfXmlStreaming()
        {
            RdfXmlParser parser = new RdfXmlParser(RdfXmlParserMode.Streaming);

            parser.TraceParsing = true;
            Graph g = new Graph();

            parser.Load(g, "resources\\example.rdf");

            TestTools.ShowGraph(g);
        }
コード例 #23
0
        //static void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        //{
        //    if (e.PropertyName == "ConsoleOutput")
        //        Console.WriteLine((sender as ProcessViewModel).ConsoleOutput);
        //}

        /// <summary>
        /// https://bitbucket.org/dotnetrdf/dotnetrdf/wiki/User%20Guide
        /// </summary>
        static void TestRDF()
        {
            IGraph       g          = new Graph();
            RdfXmlParser fileParser = new RdfXmlParser();

            //fileParser.Load(g, "schema.xml");
            fileParser.Load(g, "TestRdf.xml");

            //SparqlQueryParser queryParser = new SparqlQueryParser();
            //queryParser.ParseFromString("SELECT * WHERE { ?s a ?type }");
            //VDS.RDF.Writing.StringWriter.Write(g, new RdfXmlWriter())

            StringBuilder div = new StringBuilder();

            XElement rdf = XElement.Parse(VDS.RDF.Writing.StringWriter.Write(g, new RdfXmlWriter()));

            foreach (XElement element in rdf.Elements())
            {
                div.AppendFormat("<div itemscope itemtype=\"{0}/{1}\">", element.Name.NamespaceName.TrimEnd('/'), element.Name.LocalName);
                div.AppendLine();
                foreach (XElement content in element.Elements())
                {
                    div.AppendFormat("<meta itemprop=\"{0}\" content=\"{1}\">", content.Name.LocalName, content.Value);
                    div.AppendLine();
                }
                div.AppendLine("</div>");
            }

            var output = g.ExecuteQuery("SELECT * WHERE { ?s a ?type }");



            SparqlParameterizedString query = new SparqlParameterizedString();

            query.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
            query.Namespaces.AddNamespace("owl", new Uri("http://www.w3.org/2002/07/owl#"));
            query.Namespaces.AddNamespace("xsd", new Uri("http://www.w3.org/2001/XMLSchema#"));
            query.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#"));
            query.Namespaces.AddNamespace("schema", new Uri("http://schema.org/"));
            query.Namespaces.AddNamespace("fact", new Uri("http://www.co-ode.org/ontologies/ont.owl#"));

            query.CommandText = "SELECT * WHERE { ?organization rdf:type fact:UniqueCompany }";

            var output2 = g.ExecuteQuery(query);

//            var output2 = g.ExecuteQuery(@"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
//										PREFIX owl: <http://www.w3.org/2002/07/owl#>
//										PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
//										PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
//										PREFIX schema: <http://schema.org/>
//										PREFIX fact:<http://www.co-ode.org/ontologies/ont.owl#>
//										SELECT *
//										WHERE { ?organization rdf:type fact:UniqueCompany }");
        }
コード例 #24
0
        static void Main(string[] args)
        {
            string path = @"..\..\..\..\..\src\MakeMetadata\MakeMetadata\nuspec2package.xslt";

            XslCompiledTransform transform = CreateTransform(path);

            string baseAddress = "http://tempuri.org/base/";

            XsltArgumentList arguments = new XsltArgumentList();

            arguments.AddParam("base", "", baseAddress);

            //foreach (KeyValuePair<string, string> arg in transformArgs)
            //{
            //    arguments.AddParam(arg.Key, "", arg.Value);
            //}

            XDocument nuspec = XDocument.Load(new StreamReader(@"c:\data\extended\ledzep.boxset.v1.nuspec"));

            XDocument rdfxml = new XDocument();

            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                transform.Transform(nuspec.CreateReader(), arguments, writer);
            }

            Console.WriteLine(rdfxml);

            Console.WriteLine();

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            XmlDocument  doc          = new XmlDocument();

            doc.Load(rdfxml.CreateReader());
            IGraph graph = new Graph();

            rdfXmlParser.Load(graph, doc);

            string subject = graph.GetTriplesWithPredicateObject(
                graph.CreateUriNode(new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
                graph.CreateUriNode(new Uri("http://nuget.org/schema#Package")))
                             .First()
                             .Subject
                             .ToString();

            CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter();

            turtleWriter.DefaultNamespaces.AddNamespace("nuget", new Uri("http://nuget.org/schema#"));
            turtleWriter.DefaultNamespaces.AddNamespace("package", new Uri(subject + "#"));

            turtleWriter.PrettyPrintMode  = true;
            turtleWriter.CompressionLevel = 10;
            turtleWriter.Save(graph, Console.Out);
        }
コード例 #25
0
        public void ParsingRdfXmlResetDefaultNamespace()
        {
            IGraph g      = new Graph();
            var    parser = new RdfXmlParser(RdfXmlParserMode.Streaming);

            parser.Load(g, @"resources\rdfxml-defaultns-scope.xml");
            var resourceNode = g.CreateUriNode(UriFactory.Create("http://example.org/thing/1"));
            var p1Node       = g.CreateUriNode(UriFactory.Create("http://example.org/ns/b#p1"));
            var p2Node       = g.CreateUriNode(UriFactory.Create("http://example.org/ns/a#p2"));
            var triples      = g.GetTriplesWithSubject(resourceNode).ToList();

            Assert.False(g.IsEmpty);
            Assert.Equal(3, triples.Count);
            Assert.NotNull(p2Node);
            Assert.Single(g.GetTriplesWithSubjectPredicate(resourceNode, p1Node));
            Assert.Single(g.GetTriplesWithSubjectPredicate(resourceNode, p2Node));
        }
コード例 #26
0
ファイル: RdfService.cs プロジェクト: YasikYa/SemanticWeb
        public bool Validate()
        {
            var parser = new RdfXmlParser();

            try
            {
                parser.Load(new Graph(), SAVE_TO);
                return(true);
            }
            catch (RdfParseException ex)
            {
                Console.WriteLine($"Parsing error: {ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"Inner message: {ex.InnerException.Message}");
                }
                return(false);
            }
        }
コード例 #27
0
        /// <summary>
        /// Updates the underlying store with this as the new representation of the identified resource
        /// </summary>
        /// <param name="resourceUri">The resource for whom this is the representation</param>
        /// <param name="resourceDescription">The rdf xml document that describes the resource</param>
        public override void ApplyFragment(string resourceUri, XDocument resourceDescription)
        {
            try
            {
                var g            = new Graph();
                var rdfXmlParser = new RdfXmlParser();
                rdfXmlParser.Load(g, new StringReader(resourceDescription.ToString()));
                var ntWriter = new NTriplesWriter();
                var data     = StringWriter.Write(g, ntWriter);

                var sparqlUpdate = "";
                sparqlUpdate += "DELETE { GRAPH <" + GraphUri + "> { <" + resourceUri + ">  ?x  ?y }}";
                sparqlUpdate += "USING <" + GraphUri + "> WHERE {<" + resourceUri + "> ?x ?y } ;";
                sparqlUpdate += "INSERT DATA { GRAPH <" + GraphUri + "> {  ";
                sparqlUpdate += data;
                sparqlUpdate += " }};";

                // execute update
                var wr = WebRequest.Create(SparqlEndpoint) as HttpWebRequest;
                wr.ContentType = "application/sparql-update";
                wr.Method      = "POST";
                var ds    = wr.GetRequestStream();
                var bytes = Encoding.ASCII.GetBytes(sparqlUpdate);
                ds.Write(bytes, 0, bytes.Length);
                var resp = wr.GetResponse() as HttpWebResponse;

                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Logging.LogDebug("Update successful");
                }
                else
                {
                    Logging.LogDebug("Not a 200");
                }
                resp.Close();
            } catch (Exception ex)
            {
                Logging.LogError(1, "Unable to apply fragment for resourceUri {0} {1}", ex.Message, ex.StackTrace);
            }
        }
コード例 #28
0
        private Graph GetXmlDocumentAsGraph()
        {
            var g = new Graph();

            if (_xmlParser == null)
            {
                _xmlParser = new RdfXmlParser(RdfXmlParserMode.DOM);
                //This is not to store the URIs in a static list by dotNetRDF (uses up a lot of mem)
                Options.InternUris = false;
            }

            _xmlParser.Load(g, _output);

            //add namespaces from the XML doc to the graph
            foreach (var nsPrefix in _namespaces.Keys)
            {
                if (!g.NamespaceMap.HasNamespace(nsPrefix))
                {
                    g.NamespaceMap.AddNamespace(nsPrefix, new Uri(_namespaces[nsPrefix]));
                }
            }

            return(g);
        }
コード例 #29
0
ファイル: OslcQueryResult.cs プロジェクト: nenaaki/oslc4net
        private void InitializeRdf()
        {
            if (!rdfInitialized)
            {
                rdfInitialized = true;
                rdfGraph       = new Graph();
                Stream       stream       = response.Content.ReadAsStreamAsync().Result;
                IRdfReader   parser       = new RdfXmlParser();
                StreamReader streamReader = new StreamReader(stream);

                using (streamReader)
                {
                    parser.Load(rdfGraph, streamReader);

                    //Find a resource with rdf:type of oslc:ResourceInfo
                    rdfType = rdfGraph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
                    IUriNode             responseInfo = rdfGraph.CreateUriNode(new Uri(OslcConstants.OSLC_CORE_NAMESPACE + "ResponseInfo"));
                    IEnumerable <Triple> triples      = rdfGraph.GetTriplesWithPredicateObject(rdfType, responseInfo);

                    //There should only be one - take the first
                    infoResource = triples.Count() == 0 ? null : (triples.First().Subject as IUriNode);
                }
            }
        }
コード例 #30
0
        public override List <IDataObject> ToDataObjects(string graphName, ref XDocument xDocument)
        {
            _dataObjects = null;

            try
            {
                if (xDocument != null)
                {
                    _graphMap = _mapping.FindGraphMap(graphName);

                    if (_graphMap != null && _graphMap.classTemplateMaps.Count > 0)
                    {
                        XmlDocument xmlDocument = new XmlDocument();
                        using (XmlReader xmlReader = xDocument.CreateReader())
                        {
                            xmlDocument.Load(xmlReader);
                        }
                        xDocument.Root.RemoveAll();

                        RdfXmlParser parser = new RdfXmlParser();
                        Graph        graph  = new Graph();
                        parser.Load(graph, xmlDocument);
                        xmlDocument.RemoveAll();

                        // load graph to memory store to allow querying locally
                        _memoryStore = new TripleStore();
                        _memoryStore.Add(graph);
                        graph.Dispose();

                        if (_memoryStore != null)
                        {
                            ClassMap      rootClassMap       = _graphMap.classTemplateMaps.First().classMap;
                            string        rootClassId        = rootClassMap.id;
                            List <string> rootClassInstances = GetClassInstances(rootClassId);

                            if (rootClassInstances.Count > 0)
                            {
                                _dataObjects        = new List <IDataObject>();
                                _dataRecords        = new Dictionary <string, string> [rootClassInstances.Count];
                                _relatedRecordsMaps = new Dictionary <string, List <Dictionary <string, string> > > [rootClassInstances.Count];
                                _relatedObjectPaths = new List <string>();

                                for (int i = 0; i < rootClassInstances.Count; i++)
                                {
                                    List <string> rootClassInstance = new List <string> {
                                        rootClassInstances[i]
                                    };

                                    _dataRecords[i]        = new Dictionary <string, string>();
                                    _relatedRecordsMaps[i] = new Dictionary <string, List <Dictionary <string, string> > >();

                                    ProcessInboundClass(i, rootClassMap, rootClassInstance);

                                    if (_primaryClassificationStyle == ClassificationStyle.Both)
                                    {
                                        TemplateMap classificationTemplate = _classificationConfig.TemplateMap;
                                        ProcessInboundTemplates(i, rootClassInstance, new List <TemplateMap> {
                                            classificationTemplate
                                        });
                                    }

                                    try
                                    {
                                        IDataObject dataObject = CreateDataObject(_graphMap.dataObjectName, i);
                                        _dataObjects.Add(dataObject);
                                    }
                                    catch (Exception e)
                                    {
                                        StringBuilder builder = new StringBuilder();
                                        Dictionary <string, string> dataRecord = _dataRecords[i];

                                        builder.AppendLine("Error creating data object. " + e);
                                        builder.AppendLine("Data Record: ");

                                        foreach (var pair in dataRecord)
                                        {
                                            builder.AppendLine("\t" + pair.Key + ": " + pair.Value);
                                        }

                                        _logger.Error(builder.ToString());
                                    }
                                }

                                // fill related data objects and append them to top level data objects
                                if (_relatedObjectPaths != null && _relatedObjectPaths.Count > 0)
                                {
                                    ProcessRelatedItems();
                                    CreateRelatedObjects();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error in ToDataObjects: " + ex);
                throw ex;
            }

            return(_dataObjects);
        }