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); }
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); }
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); } }
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"); }
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 }
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); } }
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"); }
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); }
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); } }
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"); }
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); }
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)); } } }
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]); }
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); } }
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); }
// 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); }
public static Pubmed LoadFromXML(string filename) { RdfXmlParser xmlParser = new RdfXmlParser(); IGraph g = new Graph(); xmlParser.Load(g, filename); return(new Pubmed(g)); }
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); }
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"); }
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); }
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); }
//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 }"); }
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); }
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)); }
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); } }
/// <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); } }
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); }
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); } } }
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); }