public void Execute() { IGraph ttlGraph = new Graph(); TurtleParser ttlparser = new TurtleParser(); try { //Load using a Filename ttlparser.Load(ttlGraph, "HelloWorld.ttl"); foreach (Triple t in ttlGraph.Triples) { Console.WriteLine(t.ToString()); } IGraph g = new Graph(); UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Barack_Obama")); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } } catch (Exception exc) { } }
public void SetUp() { _rdfLoader = Mock.Of <IRdfLoader>(); _turtleParser = Mock.Of <TurtleParser>(); _r2rmlParser = new R2RMLParser(_rdfLoader, _turtleParser); Mock.Get(_rdfLoader).Setup(f => f.LoadFromFile(It.IsAny <Graph>(), It.Is <string>(s => !s.Equals(_dirPath + _emptyFile)), _turtleParser)).Throws <FileNotFoundException>(); Mock.Get(_rdfLoader).Setup(f => f.LoadFromFile(It.IsAny <Graph>(), _dirPath + _prefixOnlyFIle, _turtleParser)) .Callback <IGraph, string, IRdfReader>((graph, filename, rdfReader) => { graph.NamespaceMap.AddNamespace("rr", UriFactory.Create("http://www.w3.org/ns/r2rml#")); graph.NamespaceMap.AddNamespace(_examplePrefix, _examplePrefixUri); }); Mock.Get(_rdfLoader).Setup(f => f.LoadFromFile(It.IsAny <Graph>(), _dirPath + _validFile, _turtleParser)) .Callback <IGraph, string, IRdfReader>((graph, filename, rdfReader) => { if (graph.IsEmpty && graph.BaseUri == null) { graph.BaseUri = UriFactory.Create("file:///" + filename); } IUriNode triplesMap = graph.CreateUriNode(UriFactory.Create(graph.BaseUri.ToString() + "#TriplesMap1")); graph.NamespaceMap.AddNamespace("rr", UriFactory.Create("http://www.w3.org/ns/r2rml#")); graph.NamespaceMap.AddNamespace(_examplePrefix, _examplePrefixUri); graph.Assert(triplesMap, graph.CreateUriNode("rr:logicalTable"), graph.CreateBlankNode("ltNode")); graph.Assert(graph.GetBlankNode("ltNode"), graph.CreateUriNode("rr:tableName"), graph.CreateLiteralNode("EMP")); graph.Assert(triplesMap, graph.CreateUriNode("rr:subjectMap"), graph.CreateBlankNode("smNode")); graph.Assert(graph.GetBlankNode("smNode"), graph.CreateUriNode("rr:template"), graph.CreateLiteralNode("http://www.example.com/employee/{EMPNO}")); graph.Assert(graph.GetBlankNode("smNode"), graph.CreateUriNode("rr:class"), graph.CreateUriNode("ex:Employee")); graph.Assert(triplesMap, graph.CreateUriNode("rr:predicateObjectMap"), graph.CreateBlankNode("pomNode")); graph.Assert(graph.GetBlankNode("pomNode"), graph.CreateUriNode("rr:predicate"), graph.CreateUriNode("ex:name")); graph.Assert(graph.GetBlankNode("pomNode"), graph.CreateUriNode("rr:objectMap"), graph.CreateBlankNode("omNode")); graph.Assert(graph.GetBlankNode("omNode"), graph.CreateUriNode("rr:column"), graph.CreateLiteralNode("ENAME")); }); }
public IGraph ParseToGraph(String path) { logger.LogFunction("ParseToGraph"); IGraph graph = new Graph(); TurtleParser ttlparser = new TurtleParser(); try { ttlparser.Load(graph, 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); } return(graph); }
public void ParsingGraphHandlerImplicitMerging() { Graph g = new Graph(); EmbeddedResourceLoader.Load(g, "VDS.RDF.Configuration.configuration.ttl"); g.SaveToFile("temp.ttl"); Graph h = new Graph(); TurtleParser parser = new TurtleParser(); parser.Load(h, "temp.ttl"); Assert.IsFalse(g.IsEmpty, "Graph should not be empty"); Assert.IsTrue(g.NamespaceMap.HasNamespace("dnr"), "Graph should have the dnr: Namespace"); Assert.IsFalse(h.IsEmpty, "Graph should not be empty"); Assert.IsTrue(h.NamespaceMap.HasNamespace("dnr"), "Graph should have the dnr: Namespace"); Assert.AreEqual(g, h, "Graphs should be equal"); parser.Load(h, "temp.ttl"); Assert.AreEqual(g.Triples.Count + 2, h.Triples.Count, "Triples count should now be 2 higher due to the merge which will have replicated the 2 triples containing Blank Nodes"); Assert.AreNotEqual(g, h, "Graphs should no longer be equal"); NTriplesFormatter formatter = new NTriplesFormatter(); foreach (Triple t in h.Triples.Where(x => !x.IsGroundTriple)) { Console.WriteLine(t.ToString(formatter)); } }
public void WritingBlankNodeOutput() { //Create a Graph and add a couple of Triples which when serialized have //potentially colliding IDs Graph g = new Graph(); g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org")); IUriNode subj = g.CreateUriNode("ex:subject"); IUriNode pred = g.CreateUriNode("ex:predicate"); IUriNode name = g.CreateUriNode("ex:name"); IBlankNode b1 = g.CreateBlankNode("autos1"); IBlankNode b2 = g.CreateBlankNode("1"); g.Assert(subj, pred, b1); g.Assert(b1, name, g.CreateLiteralNode("First Triple")); g.Assert(subj, pred, b2); g.Assert(b2, name, g.CreateLiteralNode("Second Triple")); TurtleWriter ttlwriter = new TurtleWriter(); ttlwriter.Save(g, "bnode-output-test.ttl"); TestTools.ShowGraph(g); TurtleParser ttlparser = new TurtleParser(); Graph h = new Graph(); ttlparser.Load(h, "bnode-output-test.ttl"); TestTools.ShowGraph(h); Assert.AreEqual(g.Triples.Count, h.Triples.Count, "Expected same number of Triples after serialization and reparsing"); }
public RDFStoreManager(RDFMode mode) { _graph = new Graph(); _tripleStore = new TripleStore(); _tripleStore.Add(_graph); _turtleParser = new TurtleParser(); _processor = new LeviathanQueryProcessor(this._tripleStore); _sqlQueryParser = new SparqlQueryParser(); _turtleWriter = new CompressingTurtleWriter { CompressionLevel = WriterCompressionLevel.High }; switch (mode) { case RDFMode.SAL: //doing weird shit to get the path of the library where the files are located var pathToFile = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).GetLeftPart(UriPartial.Path); var path = new Uri(pathToFile.Substring(0, pathToFile.LastIndexOf('/'))).AbsolutePath + "/Schemas/"; LoadTurtleFile(path + "Brick.ttl"); LoadTurtleFile(path + "schema.ttl"); LoadTurtleFile(path + "sal.ttl"); LoadTurtleFile(path + "sali.ttl"); break; case RDFMode.Generic: break; default: break; } }
static void Test0() { IGraph g = new Graph(); TurtleParser parser = new TurtleParser(); parser.Load(g, "datatypes.test.ttl"); StringWriter stringWriter = new StringWriter(); JToken frame; using (JsonReader reader = new JsonTextReader(new StreamReader("datatypes.context.json"))) { frame = JToken.Load(reader); } JsonLdWriter jsonLdWriter = new JsonLdWriter(); jsonLdWriter.Frame = frame; jsonLdWriter.Save(g, stringWriter); JToken compacted = JToken.Parse(stringWriter.ToString()); Console.WriteLine(compacted); }
public void GraphWithBNodeEquality() { try { Console.WriteLine("Testing Graph Equality when the Graphs have Blank Nodes"); Graph g = new Graph(); Graph h = new Graph(); TurtleParser ttlparser = new TurtleParser(); ttlparser.Load(g, "MergePart1.ttl"); ttlparser.Load(h, "MergePart1.ttl"); Assert.AreEqual(g.BaseUri, h.BaseUri, "The Base URIs of the Graphs should not be affected by the Load and so should be both null"); //TestTools.CompareGraphs(g, h, true); Dictionary <INode, INode> mapping; bool equals = g.Equals(h, out mapping); Assert.IsTrue(equals, "Graphs should have been equal"); if (mapping != null) { Console.WriteLine("Blank Node Mapping was:"); foreach (KeyValuePair <INode, INode> pair in mapping) { Console.WriteLine(pair.Key.ToString() + " => " + pair.Value.ToString()); } } } catch (RdfParseException parseEx) { throw; } catch (Exception ex) { throw; } }
private static int Handle(FileInfo model) { bool failed = false; try { IGraph graph = new Graph(); TurtleParser ttlparser = new TurtleParser(); ttlparser.Load(graph, model.FullName); Console.WriteLine($"OK: {model.FullName}"); } catch (RdfParseException parseEx) { //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc. Console.Error.WriteLine($"FAIL: {model.FullName}"); Console.Error.WriteLine(parseEx.Message); failed = true; } catch (RdfException rdfEx) { //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace Console.Error.WriteLine($"FAIL: {model.FullName}"); Console.WriteLine(rdfEx.Message); failed = true; } return((failed) ? 1 : 0); }
public void ParsingGraphHandlerImplicitMerging() { Graph g = new Graph(); EmbeddedResourceLoader.Load(g, "VDS.RDF.Configuration.configuration.ttl"); g.SaveToFile("graph_handler_tests_temp.ttl"); Graph h = new Graph(); TurtleParser parser = new TurtleParser(); parser.Load(h, "graph_handler_tests_temp.ttl"); Assert.False(g.IsEmpty, "Graph should not be empty"); Assert.True(g.NamespaceMap.HasNamespace("dnr"), "Graph should have the dnr: Namespace"); Assert.False(h.IsEmpty, "Graph should not be empty"); Assert.True(h.NamespaceMap.HasNamespace("dnr"), "Graph should have the dnr: Namespace"); Assert.Equal(g, h); parser.Load(h, "graph_handler_tests_temp.ttl"); Assert.Equal(g.Triples.Count + 2, h.Triples.Count); Assert.NotEqual(g, h); NTriplesFormatter formatter = new NTriplesFormatter(); foreach (Triple t in h.Triples.Where(x => !x.IsGroundTriple)) { Console.WriteLine(t.ToString(formatter)); } }
public void RunVocab(String[] args) { if (args.Length < 2) { Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -vocab mode"); return; } if (File.Exists(args[1])) { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot output the configuration vocabulary to " + args[1] + " as a file already exists at that location"); return; } TurtleParser ttlparser = new TurtleParser(); StreamReader reader = new StreamReader(Assembly.GetAssembly(typeof(IGraph)).GetManifestResourceStream("VDS.RDF.Configuration.configuration.ttl")); Graph g = new Graph(); ttlparser.Load(g, reader); IRdfWriter writer; try { writer = MimeTypesHelper.GetWriterByFileExtension(MimeTypesHelper.GetTrueFileExtension(args[1])); } catch (RdfWriterSelectionException) { writer = new CompressingTurtleWriter(WriterCompressionLevel.High); } writer.Save(g, args[1]); Console.WriteLine("rdfWebDeploy: Configuration Vocabulary output to " + args[1]); }
public void GraphWithBNodeEquality() { Console.WriteLine("Testing Graph Equality when the Graphs have Blank Nodes"); Graph g = new Graph(); Graph h = new Graph(); TurtleParser ttlparser = new TurtleParser(); ttlparser.Load(g, "resources\\MergePart1.ttl"); ttlparser.Load(h, "resources\\MergePart1.ttl"); Assert.Equal(g.BaseUri, h.BaseUri); //TestTools.CompareGraphs(g, h, true); Dictionary <INode, INode> mapping; bool equals = g.Equals(h, out mapping); Assert.True(@equals, "Graphs should have been equal"); if (mapping != null) { Console.WriteLine("Blank Node Mapping was:"); foreach (KeyValuePair <INode, INode> pair in mapping) { Console.WriteLine(pair.Key.ToString() + " => " + pair.Value.ToString()); } } }
private static IRdfReader CreateReader(string mediaType) { IRdfReader result = null; switch (mediaType) { case TextTurtle: result = new TurtleParser(); break; case ApplicationRdfXml: case ApplicationOwlXml: result = new RdfXmlParser(); break; case ApplicationLdJson: result = new JsonLdParser(); break; default: throw new InvalidOperationException(String.Format("Media type '{0}' is not supported.", mediaType)); } return(result); }
static void Main(string[] args) { try { PlayWithGraph p = new PlayWithGraph(); p.PlayWithOverview(); p.PlayWithHelloWorld(); p.PlayWithReadingRdf(); p.TesPlayWithWritingRdft(); p.TestCompressingTurtleWriter(); p.TestHtmlWriter(); WorkingWithGraphs w = new WorkingWithGraphs(); w.TestBaseUri(); w.TestGetNodes(); w.SelectingTriples(); w.MergingGraphs(); Test1(); IGraph g = new Graph(); TurtleParser ttlparser = new TurtleParser(); //Load using a Filename ttlparser.Load(g, @"C:\Users\philippe\Documents\GitHub\DotNetRDFExample\DotNetRDFExample\Files\Test12.ttl"); //First we need an instance of the SparqlQueryParser SparqlQueryParser parser = new SparqlQueryParser(); //Then we can parse a SPARQL string into a query string query = File.ReadAllText(@"C:\Users\philippe\Documents\GitHub\DotNetRDFExample\DotNetRDFExample\Files\query1.txt"); SparqlQuery q = parser.ParseFromString(query); SparqlResultSet o = g.ExecuteQuery(q) as SparqlResultSet; //Create a formatter INodeFormatter formatter = new TurtleFormatter(); foreach (SparqlResult result in o) { Console.WriteLine(result.ToString(formatter)); } } catch (RdfParseException parseEx) { //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc. Console.WriteLine("Parser Error"); Console.WriteLine(parseEx.Message); } catch (RdfException rdfEx) { //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace Console.WriteLine("RDF Error"); Console.WriteLine(rdfEx.Message); } }
// Load RDF content from ttl file public static Graph LoadFromFileTurtle(String fileName) { Graph g = new Graph(); TurtleParser ttlParser = new TurtleParser(); ttlParser.Load(g, fileName); return(g); }
public static IGraph Load(string name) { TurtleParser parser = new TurtleParser(); IGraph g = new Graph(); parser.Load(g, new StreamReader(Utils.GetResourceStream(name))); return(g); }
public static void parse(string fn, Action <Triple, int> onTriple) { var ttlparser = new TurtleParser(); Options.InternUris = false; using (var graph = new MyGraph(onTriple)) using (var rdr = new StreamReader(fn)) ttlparser.Load(graph, rdr); }
public void StorageNativeGraph() { //Load in our Test Graph TurtleParser ttlparser = new TurtleParser(); Graph g = new Graph(); ttlparser.Load(g, "resources\\Turtle.ttl"); Console.WriteLine("Loaded Test Graph OK"); Console.WriteLine("Test Graph contains:"); Assert.False(g.IsEmpty, "Test Graph should be non-empty"); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } Console.WriteLine(); //Create our Native Managers List <IStorageProvider> managers = new List <IStorageProvider>() { new InMemoryManager(), #if NET40 VirtuosoTest.GetConnection() #endif }; //Save the Graph to each Manager foreach (IStorageProvider manager in managers) { Console.WriteLine("Saving using '" + manager.GetType().ToString() + "'"); manager.SaveGraph(g); Console.WriteLine("Saved OK"); Console.WriteLine(); } //Load Back from each Manager foreach (IStorageProvider manager in managers) { Console.WriteLine("Loading using '" + manager.GetType().ToString() + "' with a NativeGraph"); StoreGraphPersistenceWrapper native = new StoreGraphPersistenceWrapper(manager, g.BaseUri); Console.WriteLine("Loaded OK"); Assert.False(native.IsEmpty, "Retrieved Graph should contain Triples"); Assert.Equal(g.Triples.Count, native.Triples.Count); Console.WriteLine("Loaded Graph contains:"); foreach (Triple t in native.Triples) { Console.WriteLine(t.ToString()); } Console.WriteLine(); native.Dispose(); } }
/// <summary> /// Loads the Default Profile which is embedded in this assembly /// </summary> private void LoadDefaultProfile() { StreamReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("VDS.RDF.LinkedData.Profiles.DefaultExpansionProfile.ttl")); TurtleParser ttlparser = new TurtleParser(); Graph g = new Graph(); ttlparser.Load(g, reader); this.Initialise(g); }
public void WritingRdfXmlComplex() { Graph g = new Graph(); TurtleParser parser = new TurtleParser(); parser.Load(new PagingHandler(new GraphHandler(g), 1000), "resources\\chado-in-owl.ttl"); this.CheckRoundTrip(g); }
static void Main(string[] args) { // For simple queries: //First we need an instance of the SparqlQueryParser SparqlQueryParser parser = new SparqlQueryParser(); //For complex queries //Create a Parameterized String SparqlParameterizedString queryString = new SparqlParameterizedString(); //Add a namespace declaration queryString.Namespaces.AddNamespace("ex", new Uri("http://www.w3.org/ns/dcat#")); //Set the SPARQL command //For more complex queries we can do this in multiple lines by using += on the //CommandText property //Note we can use @name style parameters here queryString.CommandText = "SELECT * WHERE { ?s ex:property @value }"; //Inject a Value for the parameter queryString.SetUri("value", new Uri("http://example.org/value")); //When we call ToString() we get the full command text with namespaces appended as PREFIX //declarations and any parameters replaced with their declared values Console.WriteLine(queryString.ToString()); //We can turn this into a query by parsing it as in our previous example SparqlQueryParser p = new SparqlQueryParser(); SparqlQuery query = p.ParseFromString(queryString); IGraph g = new Graph(); g.LoadFromFile("dcat-ap_2.0.1.rdf"); foreach (Triple t in g.Triples) { Console.WriteLine(string.Concat("PREDICATE: ", t.Predicate)); Console.WriteLine(string.Concat("SUBJECT: ", t.Subject)); Console.WriteLine(string.Concat("OBJECT: ", t.Object)); } TurtleParser turtleParser = new TurtleParser(); Graph graph = new Graph(); graph.LoadFromFile("dcat-ap_2.0.1.rdf"); var ds = graph.GetUriNode("dct:title"); }
public void WritingHtmlSchemaWriter() { //Load the Graph from within the Assembly Graph g = new Graph(); TurtleParser parser = new TurtleParser(); parser.Load(g, new StreamReader(typeof(IGraph).GetTypeInfo().Assembly.GetManifestResourceStream("VDS.RDF.Configuration.configuration.ttl"), Encoding.UTF8)); //Now generate the HTML file HtmlSchemaWriter writer = new HtmlSchemaWriter(); writer.Save(g, "configSchema.html"); }
private void button1_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog(); openDlg.DefaultExt = ".ttl"; openDlg.Filter = "Turtle|*.ttl"; //|Owl|*.owl|All Files|*.*"; openDlg.Title = "Graph to import"; if (openDlg.ShowDialog(this) == true) { scheduleGraph = new Graph(); TurtleParser parser = new TurtleParser(); parser.Load(scheduleGraph, openDlg.FileName); } }
private static IGraph Load(string source) { var result = new Graph(); var graphHandler = new GraphHandler(result); var strippingHandler = new StripStringHandler(graphHandler); var parser = new TurtleParser(); using (var reader = new StringReader(source)) { parser.Load(strippingHandler, reader); } return(result); }
private void ParsingUsingWriteThroughHandler(Type formatterType) { if (!System.IO.File.Exists("write_through_handler_tests_temp.ttl")) { Graph g = new Graph(); EmbeddedResourceLoader.Load(g, "VDS.RDF.Configuration.configuration.ttl"); g.SaveToFile("write_through_handler_tests_temp.ttl"); } WriteThroughHandler handler = new WriteThroughHandler(formatterType, Console.Out, false); TurtleParser parser = new TurtleParser(); parser.Load(handler, "write_through_handler_tests_temp.ttl"); }
public void ParsingGraphHandlerImplicitInitialBaseUri() { Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/"); String fragment = "<subject> <predicate> <object> ."; TurtleParser parser = new TurtleParser(); parser.Load(g, new StringReader(fragment)); Assert.False(g.IsEmpty, "Graph should not be empty"); Assert.Equal(1, g.Triples.Count); }
public void ParsingMultiHandlerGraphWithFactory() { EnsureTestData(); Graph g = new Graph(); GraphHandler h = new GraphHandler(g); MultiHandler handler = new MultiHandler(new IRdfHandler[] { h }, g); TurtleParser parser = new TurtleParser(); parser.Load(handler, "multi_handler_tests_temp.ttl"); Assert.Same(g, g.Triples.First().Graph); }
public void ParsingMultiHandlerGraphAndNull() { EnsureTestData(); Graph g = new Graph(); GraphHandler handler1 = new GraphHandler(g); NullHandler handler2 = new NullHandler(); MultiHandler handler = new MultiHandler(new IRdfHandler[] { handler1, handler2 }); TurtleParser parser = new TurtleParser(); parser.Load(handler, "multi_handler_tests_temp.ttl"); }
private void UpdateTupleEditor() { try { InitGraph(); var parser = new TurtleParser(); TextReader sr = new StringReader(textBoxTurtleEditor.Text); parser.Load(G, sr); ReportMsg(""); } catch (Exception ex) { ReportMsg(ex); } }
public void ParsingChainedHandlerGraphAndNull() { EnsureTestData(); Graph g = new Graph(); GraphHandler handler1 = new GraphHandler(g); NullHandler handler2 = new NullHandler(); ChainedHandler handler = new ChainedHandler(new IRdfHandler[] { handler1, handler2 }); TurtleParser parser = new TurtleParser(); parser.Load(handler, "temp.ttl"); }