public void Load(string subjectUri) { try { Options.UriLoaderCaching = false; UriLoader.Load(this, new Uri(subjectUri)); } catch { } }
public void SerializationDataContractGraph3() { Skip.IfNot(TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing), "Test Config marks Remote Parsing as unavailable, test cannot be run"); Graph g = new Graph(); UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Ilkeston")); this.TestGraphSerializationDataContract(g); }
public void ParsingUriLoaderGraphHandlerExplicit() { Graph g = new Graph(); GraphHandler handler = new GraphHandler(g); UriLoader.Load(handler, new Uri("http://www.dotnetrdf.org/configuration#")); TestTools.ShowGraph(g); Assert.False(g.IsEmpty, "Graph should not be empty"); }
public void TestReplaceMethod() { string baseStr = "https://[DOMAIN]/ads/"; string substitutionStr = "www.gunsexchange.ca"; string expectedStr = "https://www.gunsexchange.ca/ads/"; UriLoader ldr = new UriLoader(); ldr.ReplaceField(ref baseStr, "DOMAIN", substitutionStr); Assert.AreEqual(expectedStr, baseStr); }
private void fromURIToolStripMenuItem_Click_1(object sender, EventArgs e) { if (listViewGraph.SelectedItems.Count != 1) { MessageBox.Show("no graph is selected"); return; } var graphUri = (string)listViewGraph.SelectedItems[0].Tag; var tabPage = GetTabPage(graphUri); if (tabPage != null) { var graphEditor = (GraphEditor)tabPage.Tag; if (graphEditor.RequestSave()) { if ( MessageBox.Show(string.Format("save graph before closing graph {0}", graphEditor.GraphUri), "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes) { graphEditor.SaveGraph(); } } tabControlGraph.TabPages.Remove(tabPage); } var form = new SingleForm { Title = "Set URI", Label = "URI" }; if (form.ShowDialog() != DialogResult.OK) { return; } var ng = new Graph(); try { UriLoader.Load(ng, new Uri(form.Content)); } catch (Exception ex) { MessageBox.Show("Invalid format. " + ex); return; } var g = new Graph(); fuseki.LoadGraph(g, graphUri); var cnt = ng.Triples.Count(g.Assert); fuseki.SaveGraph(g); MessageBox.Show(string.Format("successfully insert {0} triples", cnt)); }
public void WritingCollections() { Graph g = new Graph(); Options.UriLoaderCaching = false; UriLoader.Load(g, new Uri("http://www.wurvoc.org/vocabularies/om-1.6/Kelvin_scale")); CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(WriterCompressionLevel.High); ttlwriter.Save(g, Console.Out); }
/// <summary> /// Adds a Graph into the Triple Store which is retrieved from the given Uri using the chosen Merging Behaviour /// </summary> /// <param name="graphUri">Graph to add</param> /// <param name="mergeIfExists">Whether the Graph should be merged with an existing Graph with the same Base Uri</param> /// <remarks> /// <strong>Important:</strong> Under Silverlight/Windows Phone 7 this will happen asynchronously so the Graph may not be immediatedly available in the store /// </remarks> public virtual void AddFromUri(Uri graphUri, bool mergeIfExists) { Graph g = new Graph(); #if !SILVERLIGHT UriLoader.Load(g, graphUri); this._graphs.Add(g, mergeIfExists); #else UriLoader.Load(g, graphUri, (gr, _) => { this._graphs.Add(gr, mergeIfExists); }, null); #endif }
private void btnImportUri_Click(object sender, EventArgs e) { if (this.txtSourceUri.Text.Equals(string.Empty)) { MessageBox.Show("Please enter a URI you wish to import RDF from...", "No URI Specified"); } else { Graph g = new Graph(); try { UriLoader.Load(g, new Uri(this.txtSourceUri.Text)); try { if (this._dataset.HasGraph(g.BaseUri)) { int triplesBefore = this._dataset[g.BaseUri].Triples.Count; this._dataset[g.BaseUri].Merge(g); this._tripleCount += this._dataset[g.BaseUri].Triples.Count - triplesBefore; } else { this._dataset.AddGraph(g); this._tripleCount += g.Triples.Count; } this.LogImportSuccess(new Uri(this.txtSourceUri.Text), 1, g.Triples.Count); } catch (Exception ex) { this.LogImportFailure(new Uri(this.txtSourceUri.Text), ex); MessageBox.Show("An error occurred trying to add the RDF Graph to the Dataset:\n" + ex.Message, "URI Import Error"); return; } } catch (UriFormatException uriEx) { MessageBox.Show("The URI you have entered is malformed:\n" + uriEx.Message, "Malformed URI"); } catch (Exception ex) { this.LogImportFailure(new Uri(this.txtSourceUri.Text), ex); MessageBox.Show("An error occurred while loading RDF from the given URI:\n" + ex.Message, "URI Import Error"); return; } this._dataset.Flush(); this.stsGraphs.Text = this._dataset.GraphUris.Count() + " Graphs"; this.stsTriples.Text = this._tripleCount + " Triples"; MessageBox.Show("RDF added to the Dataset OK", "URI Import Done"); } }
public static Object LoadFromUri(java.net.URL url, string baseUri, org.openrdf.rio.RDFFormat rdff) { Object obj; Uri u = new Uri(url.toString()); if (rdff == dotSesameFormats.RDFFormat.N3) { obj = new Graph(); if (baseUri != null) { ((IGraph)obj).BaseUri = new Uri(baseUri); } UriLoader.Load((IGraph)obj, u, new Notation3Parser()); } else if (rdff == dotSesameFormats.RDFFormat.NTRIPLES) { obj = new Graph(); if (baseUri != null) { ((IGraph)obj).BaseUri = new Uri(baseUri); } UriLoader.Load((IGraph)obj, u, new NTriplesParser()); } else if (rdff == dotSesameFormats.RDFFormat.RDFXML) { obj = new Graph(); if (baseUri != null) { ((IGraph)obj).BaseUri = new Uri(baseUri); } UriLoader.Load((IGraph)obj, u, new RdfXmlParser()); } else if (rdff == dotSesameFormats.RDFFormat.TRIG || rdff == dotSesameFormats.RDFFormat.TRIX) { obj = new TripleStore(); UriLoader.Load((ITripleStore)obj, u); } else if (rdff == dotSesameFormats.RDFFormat.TURTLE) { obj = new Graph(); if (baseUri != null) { ((IGraph)obj).BaseUri = new Uri(baseUri); } UriLoader.Load((IGraph)obj, u, new TurtleParser()); } else { throw new RdfParserSelectionException("The given Input Format is not supported by dotNetRDF"); } return(obj); }
public void SerializationJsonGraph3() { if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing)) { Assert.Inconclusive("Test Config marks Remote Parsing as unavailable, test cannot be run"); } Graph g = new Graph(); UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Ilkeston")); this.TestGraphSerializationJson(g); }
public void SerializationBinaryGraph3() { if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing)) { throw new SkipTestException("Test Config marks Remote Parsing as unavailable, test cannot be run"); } Graph g = new Graph(); UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Ilkeston")); this.TestGraphSerializationBinary(g); }
private void GraphToStructured(IEnumerable <Resource> input, Resource output) { ValidateMask(input, ResourceFormat.GraphMask); var graph = new Graph(); foreach (var file in input) { if (file.Format == ResourceFormat.RdfGeneric) { if (file.TargetPath == null) { throw new ApplicationException("Standard input resource must have a concrete format specified."); } UriLoader.Load(graph, ResolveUri(file.TargetPath)); } else { var rdfReader = GetReader(file.Format); using (var reader = new StreamReader(OpenInput(file.TargetPath), true)) { var baseUri = GetBaseUri(file.TargetPath); graph.BaseUri = baseUri != null ? new Uri(baseUri) : null; rdfReader.Load(graph, reader); } } } var root = graph.CreateUriNode(new Uri(GetBaseUri(output.TargetPath))); if (!graph.GetTriplesWithSubject(root).Any()) { throw new ApplicationException("Base URI must refer to an existing root!"); } using (var writer = XmlWriter.Create(OpenOutput(output.TargetPath), XmlWriterSettings)) { switch (output.Format) { case ResourceFormat.Xml: new RdfXmlConverter(graph).Write(writer, root); break; case ResourceFormat.XmlXPath: new RdfXPathNavigator(graph, root).WriteSubtree(writer); break; default: throw new ApplicationException("Unsupported output format!"); } } }
/// <summary> /// Implements the import /// </summary> /// <param name="handler">Handler</param> protected override void ImportUsingHandler(IRdfHandler handler) { this.Information = "Importing from URI " + this._u.AbsoluteUri; try { //Assume a RDF Graph UriLoader.Load(handler, this._u); } catch (RdfParserSelectionException) { //Assume a RDF Dataset UriLoader.LoadDataset(handler, this._u); } }
public void CacheUpdatesFileCreationTimeOnReload() { var g = new Graph(); var uri = new Uri(_serverFixture.Server.Urls[0] + "/rvesse.ttl"); UriLoader.Load(g, uri); Assert.True(UriLoader.IsCached(uri)); Thread.Sleep(UriLoader.CacheDuration + TimeSpan.FromMilliseconds(500)); Assert.True(UriLoader.IsCached(uri)); Assert.False(UriLoader.Cache.HasLocalCopy(uri, true)); UriLoader.Load(g, uri); Assert.True(UriLoader.IsCached(uri)); Assert.True(UriLoader.Cache.HasLocalCopy(uri, true)); }
private Uri ReadRemoteTripleFormat(Uri graph, Uri location, RdfSerializationFormat format) { using (VDS.RDF.Storage.VirtuosoManager m = new VDS.RDF.Storage.VirtuosoManager(CreateConnectionString())) { using (VDS.RDF.Graph g = new VDS.RDF.Graph()) { UriLoader.Load(g, location); g.BaseUri = graph; m.SaveGraph(g); } } return(graph); }
public void ServiceDescriptionDescriptionUriSparqlServer() { EnsureIIS(); String path = TestConfigManager.GetSetting(TestConfigManager.LocalGraphStoreUri) + "description"; Console.WriteLine("Making an request for the Service Description from the web demos SPARQL Server at " + path); Console.WriteLine(); NTriplesFormatter formatter = new NTriplesFormatter(); Graph g = new Graph(); UriLoader.Load(g, new Uri(path)); TestTools.ShowGraph(g); Assert.IsFalse(g.IsEmpty, "A non-empty Service Description Graph should have been returned"); }
public override void Convert() { if (this.ConversionHandler == null) { throw new Exception("Cannot convert the Input URI '" + this.SourceUri.ToString() + "' as rdfConvert could not determine a Conversion Handler to use for the Conversion"); } try { UriLoader.Load(this.ConversionHandler, this.SourceUri); } catch { UriLoader.LoadDataset(this.ConversionHandler, this.SourceUri); } }
public void WritingCollections() { Graph g = new Graph(); #if !NO_URICACHE Options.UriLoaderCaching = false; #endif UriLoader.Load(g, new Uri("http://www.wurvoc.org/vocabularies/om-1.6/Kelvin_scale")); CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(WriterCompressionLevel.High); #if PORTABLE var tmpWriter = new StreamWriter(new MemoryStream()); ttlwriter.Save(g, tmpWriter); #else ttlwriter.Save(g, Console.Out); #endif }
private IGraph LoadGraph(String uri, bool fromFile) { Graph g = new Graph(); try { if (fromFile) { FileLoader.Load(g, uri); } else { Uri u = new Uri(uri); if (u.IsAbsoluteUri) { UriLoader.Load(g, u); } else { FileLoader.Load(g, uri); } } return(g); } catch (UriFormatException) { //Try loading as a file as it's not a valid URI return(this.LoadGraph(uri, true)); } catch (RdfParseException parseEx) { Console.Error.WriteLine("rdfQuery: Parser Error: Unable to parse data from URI '" + uri + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message); } catch (RdfException rdfEx) { Console.Error.WriteLine("rdfQuery: RDF Error: Unable to read data from URI '" + uri + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: RDF Error: " + rdfEx.Message); } catch (Exception ex) { Console.Error.WriteLine("rdfQuery: Error: Unable to read data from URI '" + uri + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Error: " + ex.Message); } return(null); }
public static IGraph GetGraphFromOntology(Ontology ontology) { IGraph g = new Graph(); IRdfReader r = ontology.RdfType == RdfType.TTL ? new TurtleParser() : null; if (ontology.RdfSource == RdfSource.Uri) { if (r == null) { UriLoader.Load(g, new Uri(ontology.Location)); } else { UriLoader.Load(g, new Uri(ontology.Location), r); } } else if (ontology.RdfType == RdfType.TTL) { if (ontology.RdfSource == RdfSource.String) { r.Load(g, new StringReader(ontology.Location)); } else { r.Load(g, ontology.Location); } } else { try { FileLoader.Load(g, ontology.Location); } catch (Exception e) { while (e.InnerException != null) { e = e.InnerException; } throw new Exception($"Rdf Source and Type Unknown - {ontology.Location} - cannot load as TTL from file: {e.Message}"); } } return(g); }
static void Main(string[] args) { IGraph g = new Graph(); UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Russia")); Console.WriteLine("=== TRIPLES ==="); foreach (var x in g.Triples) { if (x.Predicate.ToString().Contains("population")) { Console.WriteLine($"O={x.Object}, P={x.Predicate}, S={x.Subject}"); } } Console.WriteLine("=== QUERY ==="); SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); SparqlResultSet results = endpoint.QueryWithResultSet(@" 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 rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX : <http://dbpedia.org/resource/> PREFIX dbpedia2: <http://dbpedia.org/property/> PREFIX dbpedia: <http://dbpedia.org/> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> SELECT ?birth STR(?name) WHERE { ?person a dbo:MusicalArtist . ?person dbo:birthPlace :Moscow . ?person dbo:birthDate ?birth . ?person foaf:name ?name . } ORDER BY ?name "); foreach (SparqlResult result in results) { Console.WriteLine(result.ToString()); } Console.ReadKey(); }
public void ParsingGraphHandlerImplicitBaseUriPropogation() { try { Options.UriLoaderCaching = false; Graph g = new Graph(); UriLoader.Load(g, new Uri("http://wiki.rkbexplorer.com/id/void")); NTriplesFormatter formatter = new NTriplesFormatter(); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } } finally { Options.UriLoaderCaching = true; } }
/// <summary> /// Evaluates the Command in the given Context /// </summary> /// <param name="context">Evaluation Context</param> public override void Evaluate(SparqlUpdateEvaluationContext context) { //Q: Does LOAD into a named Graph require that Graph to be pre-existing? //if (this._graphUri != null) //{ // //When adding to specific Graph need to ensure that Graph exists // //In the case when we're adding to the default graph we'll create it if it doesn't exist // if (!context.Data.HasGraph(this._graphUri)) // { // throw new RdfUpdateException("Cannot LOAD into a Graph that does not exist in the Store"); // } //} try { //Load from the URI Graph g = new Graph(); #if SILVERLIGHT throw new PlatformNotSupportedException("The SPARQL LOAD command is not currently supported under Silverlight/Windows Phone 7"); #else UriLoader.Load(g, this._sourceUri); #endif if (context.Data.HasGraph(this._graphUri)) { //Merge the Data into the existing Graph context.Data.GetModifiableGraph(this._graphUri).Merge(g); } else { //Add New Graph to the Dataset g.BaseUri = this._graphUri; context.Data.AddGraph(g); } } catch { if (!this._silent) { throw; } } }
private void ExpandByUriLookup(UriToExpand u, ExpansionContext context, Uri lookupEndpoint) { if (u.Depth == context.Profile.MaxExpansionDepth) { return; } StringBuilder requestUri = new StringBuilder(); requestUri.Append(lookupEndpoint.ToString()); requestUri.Append(Uri.EscapeDataString(u.Uri.ToString())); Graph g = new Graph(); Thread.Sleep(HttpRequestInterval); UriLoader.Load(g, new Uri(requestUri.ToString())); this.ExpandGraph(u, g, context); }
public Form1() { InitializeComponent(); IGraph graph = new Graph(); UriLoader.Load(graph, new Uri(RDFUrl)); try { Object results = graph.ExecuteQuery("SELECT * WHERE {\r\n ?sub ?pre ?dupa.\r\n} \r\nLIMIT 10"); if (results is SparqlResultSet) { //SELECT/ASK queries give a SparqlResultSet SparqlResultSet rset = (SparqlResultSet)results; foreach (SparqlResult r in rset) { //Do whatever you want with each Result } } else if (results is IGraph) { //CONSTRUCT/DESCRIBE queries give a IGraph IGraph resGraph = (IGraph)results; foreach (Triple t in resGraph.Triples) { //Do whatever you want with each Triple } } else { //If you don't get a SparqlResutlSet or IGraph something went wrong //but didn't throw an exception so you should handle it here Console.WriteLine("ERROR"); } } catch (RdfQueryException queryEx) { //There was an error executing the query so handle it here Console.WriteLine(queryEx.Message); } }
private static IGraph GraphFromUri(Uri uri) { var incorrectBaseUri = new Uri(baseUri.AbsoluteUri.Replace(@"https://", "http://")); var uriMapping = new Dictionary <Uri, Uri> { { incorrectBaseUri, baseUri } }; var graph = new Graph(); var handler = new UriMappingHandler(new GraphHandler(graph), graph, uriMapping); var parser = MimeTypesHelper.GetParserByFileExtension(Path.GetExtension(uri.LocalPath)); graph.BaseUri = uri; UriLoader.Load(handler, uri, parser); return(graph); }
/// <summary> /// Tries to load a Graph on demand from a URI /// </summary> /// <param name="graphUri">Graph URI</param> /// <returns></returns> protected override IGraph LoadOnDemand(Uri graphUri) { if (graphUri != null) { try { Graph g = new Graph(); UriLoader.Load(g, graphUri); return(g); } catch { throw new RdfException("The Graph with the URI " + graphUri.AbsoluteUri + " does not exist in this collection"); } } else { throw new RdfException("The Graph with the URI does not exist in this collection"); } }
public IGraph LoadImport(Uri uri) { var import = new Graph(); if (uri.IsFile) { FileLoader.Load(import, uri.ToString()); } else { try { UriLoader.Load(import, uri); } catch { } } import.BaseUri = null; return(import); }
/// <summary> /// Evaluates the Command in the given Context /// </summary> /// <param name="context">Evaluation Context</param> public override void Evaluate(SparqlUpdateEvaluationContext context) { // Q: Does LOAD into a named Graph require that Graph to be pre-existing? // if (this._graphUri != null) // { // //When adding to specific Graph need to ensure that Graph exists // //In the case when we're adding to the default graph we'll create it if it doesn't exist // if (!context.Data.HasGraph(this._graphUri)) // { // throw new RdfUpdateException("Cannot LOAD into a Graph that does not exist in the Store"); // } // } try { // Load from the URI Graph g = new Graph(); UriLoader.Load(g, _sourceUri); if (context.Data.HasGraph(_graphUri)) { // Merge the Data into the existing Graph context.Data.GetModifiableGraph(_graphUri).Merge(g); } else { // Add New Graph to the Dataset g.BaseUri = _graphUri; context.Data.AddGraph(g); } } catch { if (!_silent) { throw; } } }
/// <summary> /// Adds a Graph into the Triple Store by retrieving it from the given Uri and using the selected Merge Behaviour /// </summary> /// <param name="graphUri">Uri of the Graph to add</param> /// <param name="mergeIfExists">Whether the Graph should be merged with an existing Graph with the same Base Uri</param> public override void AddFromUri(Uri graphUri, bool mergeIfExists) { //Check if it already exists bool exists = this._graphs.Contains(graphUri); if (exists && !mergeIfExists) { throw new RdfException("The Graph you tried to add already exists in the Graph Collection"); } else if (exists) { //Load into SqlGraph //The merge is implied here and will be handled by the Parsers base.AddFromUri(graphUri, mergeIfExists); } else { //Load into SqlGraph and add Graph g = new Graph(); UriLoader.Load(g, graphUri); this.Add(g, mergeIfExists); } }
public static bool DoTests(string root, string type, CompilationUnit unit, UriLoader lib, ref int id) { var all_succeeded = true; if (!Directory.Exists(root)) { Console.WriteLine("Skipping non-existent directory: " + root); return all_succeeded; } foreach (var file in GetFiles(root, "malformed")) { var collector = new DirtyCollector(); var parser = Parser.Open(file); parser.ParseFile(collector, unit, "Test" + id++); Console.WriteLine("{0} {1} {2} {3}", collector.ParseDirty ? "----" : "FAIL", "M", type, Path.GetFileNameWithoutExtension(file)); all_succeeded &= collector.ParseDirty; } var task_master = new TestTaskMaster(); task_master.AddUriHandler(lib); foreach (var file in GetFiles(root, "errors")) { bool success; try { var collector = new DirtyCollector(); var parser = Parser.Open(file); var test_type = parser.ParseFile(collector, unit, "Test" + id++); success = collector.AnalyseDirty; if (!success && test_type != null) { var tester = new CheckResult(task_master, test_type); tester.Slot(); task_master.Run(); success = !tester.Success; } } catch (Exception) { success = false; } Console.WriteLine("{0} {1} {2} {3}", success ? "----" : "FAIL", "E", type, Path.GetFileNameWithoutExtension(file)); all_succeeded &= success; } foreach (var file in GetFiles(root, "working")) { bool success; try { var collector = new DirtyCollector(); var parser = Parser.Open(file); var test_type = parser.ParseFile(collector, unit, "Test" + id++); success = !collector.AnalyseDirty && !collector.ParseDirty; if (success && test_type != null) { var tester = new CheckResult(task_master, test_type); tester.Slot(); task_master.Run(); success = tester.Success; } } catch (Exception) { success = false; } Console.WriteLine("{0} {1} {2} {3}", success ? "----" : "FAIL", "W", type, Path.GetFileNameWithoutExtension(file)); all_succeeded &= success; } return all_succeeded; }