public string GetFormattedOutput(ref Graph graph, string outputFormat) { var writer = new System.IO.StringWriter(); if (outputFormat == "jsonLd") { var jsonLdWriter = new JsonLdWriter(); var store = new TripleStore(); store.Add(graph); jsonLdWriter.Save(store, writer); } else { dynamic formattedWriter = new CompressingTurtleWriter(); if (outputFormat == "rdf/xml") { formattedWriter = new RdfXmlWriter(); } else if (outputFormat == "n triples") { formattedWriter = new NTriplesWriter(); } formattedWriter.Save(graph, writer); } return(writer.ToString()); }
private void Validates(string name) { ExtractTestData(name, out var testGraph, out var failure, out var dataGraph, out var shapesGraph); void validates() { var actual = new ShapesGraph(shapesGraph).Validate(dataGraph).Normalised; var expected = Report.Parse(testGraph).Normalised; RemoveUnnecessaryResultMessages(actual, expected); var writer = new CompressingTurtleWriter(); output.WriteLine(StringWriter.Write(expected, writer)); output.WriteLine(StringWriter.Write(actual, writer)); Assert.Equal(expected, actual); } if (failure) { Assert.ThrowsAny <Exception>((Action)validates); } else { validates(); } }
public override void onGet(object sender, HttpEventArgs e) { HttpListenerRequest request = e.request; HttpListenerResponse response = e.response; System.IO.StringWriter stringWriter = new System.IO.StringWriter(); string valueAsString = ""; if (request.AcceptTypes.Contains("application/xml")) { xmlSerializer.Serialize(stringWriter, _value); valueAsString = stringWriter.ToString(); response.ContentType = "application/xml"; } else if (request.AcceptTypes.Contains("application/json")) { valueAsString = JsonConvert.SerializeObject(_value); response.ContentType = "application/json"; } else if (request.AcceptTypes.Contains("text/turtle")) { CompressingTurtleWriter ttlWriter = new CompressingTurtleWriter(); ttlWriter.Save(RDFGraph, stringWriter); valueAsString = stringWriter.ToString(); response.ContentType = "text/turtle"; } response.OutputStream.Write(Encoding.UTF8.GetBytes(valueAsString), 0, valueAsString.Length); response.Close(); }
private INode AddConnection(IGraph config, IStorageProvider manager, String persistentFile) { if (config == null) { return(null); } ConfigurationSerializationContext context = new ConfigurationSerializationContext(config); if (manager is IConfigurationSerializable) { INode objNode = context.Graph.CreateUriNode(new Uri("dotnetrdf:storemanager:" + DateTime.Now.ToString("yyyyMMddhhmmss"))); context.NextSubject = objNode; ((IConfigurationSerializable)manager).SerializeConfiguration(context); if (persistentFile != null) { try { //Persist the graph to disk CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(); ttlwriter.Save(config, persistentFile); } catch { MessageBox.Show("Unable to persist a Connections File to disk", "Internal Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } } return(objNode); } return(null); }
private static IRdfWriter CreateWriter(string mediaType) { IRdfWriter result; switch (mediaType) { case TextTurtle: result = new CompressingTurtleWriter(); break; case ApplicationRdfXml: case ApplicationOwlXml: result = new RdfXmlWriter(); break; case ApplicationLdJson: result = new JsonLdWriter(Context); break; default: throw new InvalidOperationException(String.Format("Media type '{0}' is not supported.", mediaType)); } if (!(result is INamespaceWriter)) { return(result); } var namespaceWriter = (INamespaceWriter)result; namespaceWriter.DefaultNamespaces.AddNamespace("owl", new Uri(Owl.BaseUri)); namespaceWriter.DefaultNamespaces.AddNamespace("hydra", Hydra); namespaceWriter.DefaultNamespaces.AddNamespace("ursa", DescriptionController <IController> .VocabularyBaseUri); return(result); }
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]); }
// Save RDF content to file as turtle public static void SaveToFileTurtle(Graph g, String fileName) { CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter(); turtleWriter.CompressionLevel = 1; turtleWriter.Save(g, fileName); }
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; } }
public static void SaveToTurtleFile(this IGraph graph, string filepath) { var writer = new CompressingTurtleWriter { CompressionLevel = WriterCompressionLevel.High }; writer.Save(graph, filepath); }
private object SerializeGraph() { var writer = new CompressingTurtleWriter(); TextWriter textWriter = new StringWriter(); writer.Save(_graph, textWriter); return(textWriter.ToString()); }
public void TestCompressingTurtleWriter() { IGraph g = CreateGraph(); CompressingTurtleWriter compressingTurtleWriter = new CompressingTurtleWriter(); SaveGraph(g, compressingTurtleWriter, "Example.ttl"); }
static void Dump(IGraph graph) { CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter(); turtleWriter.DefaultNamespaces.AddNamespace("nuget", new Uri("http://nuget.org/schema#")); turtleWriter.PrettyPrintMode = true; turtleWriter.CompressionLevel = 10; turtleWriter.Save(graph, Console.Out); }
private string ConvertGraphToString(IGraph graph) { var turtleWriter = new CompressingTurtleWriter(); var sw = new System.IO.StringWriter(); turtleWriter.Save(graph, sw); var data = sw.ToString(); return(data); }
public void Remove() { this._g.Retract(this._g.GetTriplesWithSubject(this._objNode)); if (this._file != null) { CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(); ttlwriter.Save(this._g, this._file); } }
public static void Dump(IGraph graph, TextWriter writer) { CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter(); turtleWriter.DefaultNamespaces.AddNamespace("nuget", new Uri("http://nuget.org/schema#")); turtleWriter.DefaultNamespaces.AddNamespace("catalog", new Uri("http://nuget.org/catalog#")); turtleWriter.PrettyPrintMode = true; turtleWriter.CompressionLevel = 10; turtleWriter.Save(graph, writer); }
public BasicLDPGraph(Uri u) { writer = new CompressingTurtleWriter(); RDFGraph = new Graph(); dp_uri = u.ToString(); un = RDFGraph.CreateUriNode(u); addNamespaces(); addPredicateNodes(); addObjectNodes(); }
private static void SerializeTriples(IGraph graph, Stream target) { using (var writer = new StreamWriter(target, Encoding.UTF8, 4096, true)) { var serializer = new CompressingTurtleWriter(); serializer.Save(graph, writer); } target.Seek(0, SeekOrigin.Begin); }
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 override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { IServiceProvider serviceProvider = context.HttpContext.RequestServices; var response = context.HttpContext.Response; var graph = context.Object as IGraph; var writer = new CompressingTurtleWriter(); var ttl = StringWriter.Write(graph, writer); return(response.WriteAsync(ttl)); }
//protected virtual Uri CreateIndexEntry(CatalogItem item, Uri resourceUri, Guid commitId, DateTime commitTimeStamp) //{ // Uri tmpUri = GetTempUri("catalogindexpage", "ttl"); // using (IGraph pageContent = item.CreatePageContent(Context)) // { // AddCatalogEntryData(pageContent, item.GetItemType(), resourceUri, commitId, commitTimeStamp); // SaveGraph(pageContent, tmpUri).Wait(); // } // return tmpUri; //} private async Task SaveGraph(IGraph graph, Uri uri) { StringBuilder sb = new StringBuilder(); using (var stringWriter = new System.IO.StringWriter(sb)) { CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter(); turtleWriter.Save(graph, stringWriter); } StorageContent content = new StringStorageContent(sb.ToString(), "application/json", "no-store"); await Storage.Save(uri, content); }
protected override void onGet(object sender, HttpEventArgs e) { HttpListenerRequest request = e.request; HttpListenerResponse response = e.response; System.IO.StringWriter stringWriter = new System.IO.StringWriter(); CompressingTurtleWriter ttlWriter = new CompressingTurtleWriter(); ttlWriter.Save(RDFGraph, stringWriter); string graph = stringWriter.ToString(); response.OutputStream.Write(Encoding.UTF8.GetBytes(graph), 0, graph.Length); response.Close(); }
public async Task <Stream> DownloadGraph(Uri graphName) { Guard.IsValidUri(graphName); var result = _graphManagementRepo.GetGraph(graphName); var stringAsStream = new MemoryStream(); var StreamWriter = new StreamWriter(stringAsStream); CompressingTurtleWriter tw = new CompressingTurtleWriter(); tw.Save(result, StreamWriter, true); StreamWriter.Flush(); stringAsStream.Position = 0; return(stringAsStream); }
private void buildResponse(int statusCode, HttpListenerContext context, IGraph responseGraph) { context.Response.StatusCode = statusCode; try { CompressingTurtleWriter writer = new CompressingTurtleWriter(); StreamWriter responseWriter = new StreamWriter(context.Response.OutputStream); writer.Save(responseGraph, responseWriter); } catch (Exception ex) { Log.Error(ex, "Could not write to Response output: " + ex.Message); } finally { context.Response.OutputStream.Close(); } }
/// <summary> /// https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Hello-World /// </summary> public void PlayWithHelloWorld() { IGraph g = CreateGraph(); // Console.ReadLine(); NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(g, "HelloWorld.nt"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, "HelloWorld.rdf"); CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter(); turtleWriter.Save(g, "HelloWorld.ttl"); }
public void AddRecentConnection(IStorageProvider manager) { INode objNode = this.AddConnection(this._recentConnections, manager, this._recentConnectionsFile); if (objNode != null) { this.AddConnectionToMenu(manager, this._recentConnections, objNode, this.mnuRecentConnections, this._recentConnectionsFile, false); } //Check the number of Recent Connections and delete the Oldest if more than 9 INode rdfType = this._recentConnections.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)); INode storageProvider = this._recentConnections.CreateUriNode(UriFactory.Create(ConfigurationLoader.ClassStorageProvider)); List <INode> conns = (from t in this._recentConnections.GetTriplesWithPredicateObject(rdfType, storageProvider) select t.Subject).ToList(); if (conns.Count > MaxRecentConnections) { conns.Sort(); conns.Reverse(); conns.RemoveRange(0, MaxRecentConnections); //Remember the ToList() on the retract otherwise we'll hit an error foreach (INode obj in conns) { this._recentConnections.Retract(this._recentConnections.GetTriplesWithSubject(obj).ToList()); this.RemoveFromConnectionsMenu(this.mnuRecentConnections, obj); } try { //Persist the graph to disk CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(); ttlwriter.Save(this._recentConnections, this._recentConnectionsFile); } catch { MessageBox.Show("Unable to persist a Connections File to disk", "Internal Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
public void AddRecentConnection(IGenericIOManager manager) { INode objNode = this.AddConnection(this._recentConnections, manager, this._recentConnectionsFile); if (objNode != null) { ToolStripMenuItem item = new ToolStripMenuItem(); item.Text = manager.ToString(); item.Tag = new QuickConnect(this._recentConnections, objNode); item.Click += new EventHandler(QuickConnectClick); this.mnuRecentConnections.DropDownItems.Add(item); } //Check the number of Recent Connections and delete the Oldest if more than 9 List <INode> conns = this._recentConnections.GetTriplesWithPredicateObject(this._recentConnections.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)), this._recentConnections.CreateUriNode(new Uri(ConfigurationLoader.ConfigurationNamespace + ConfigurationLoader.ClassGenericManager.Substring(ConfigurationLoader.ClassGenericManager.IndexOf(':') + 1)))).Select(t => t.Subject).ToList(); if (conns.Count > MaxRecentConnections) { conns.Sort(); conns.Reverse(); conns.RemoveRange(0, MaxRecentConnections); foreach (INode obj in conns) { this._recentConnections.Retract(this._recentConnections.GetTriplesWithSubject(obj)); this.RemoveFromConnectionsMenu(this.mnuRecentConnections, obj); } try { //Persist the graph to disk CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(); ttlwriter.Save(this._recentConnections, this._recentConnectionsFile); } catch (Exception ex) { MessageBox.Show("Unable to persist a Connections File to disk", "Internal Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
public void ParsingRdfABadSyntax() { RdfAParser parser = new RdfAParser(); Graph g = new Graph(); Console.WriteLine("Tests parsing a file which has much invalid RDFa syntax in it, some triples will be produced (6-8) but most of the triples are wrongly encoded and will be ignored"); g.BaseUri = new Uri("http://www.wurvoc.org/vocabularies/om-1.6/Kelvin_scale"); FileLoader.Load(g, "resources\\bad_rdfa.html"); Console.WriteLine(g.Triples.Count + " Triples"); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } Console.WriteLine(); CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(WriterCompressionLevel.High); ttlwriter.HighSpeedModePermitted = false; ttlwriter.Save(g, "test.ttl"); }
public override void Complete(IGraph response) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(CallbackUri); request.Method = "POST"; request.ContentType = "text/turtle"; CompressingTurtleWriter writer = new CompressingTurtleWriter(); Stream requestStream = request.GetRequestStream(); StreamWriter requestWriter = new StreamWriter(requestStream); writer.Save(response, requestWriter); requestStream.Close(); try { request.GetResponse(); } catch (Exception ex) { Log.Warn(ex, "Could not perform completion request"); } }
/// <summary> /// Saves a Graph to the Store asynchronously /// </summary> /// <param name="g">Graph to save</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public override void SaveGraph(IGraph g, AsyncStorageCallback callback, object state) { // Set up the Request HttpWebRequest request; if (g.BaseUri != null) { request = (HttpWebRequest)WebRequest.Create(_baseUri + "data/" + g.BaseUri.AbsoluteUri); } else { throw new RdfStorageException("Cannot save a Graph without a Base URI to a 4store Server"); } request.Method = "PUT"; request.ContentType = MimeTypesHelper.Turtle[0]; request = ApplyRequestOptions(request); // Write the Graph as Turtle to the Request Stream CompressingTurtleWriter writer = new CompressingTurtleWriter(WriterCompressionLevel.High); SaveGraphAsync(request, writer, g, callback, state); }
/// <summary> /// Saves a Graph to a 4store instance (Warning: Completely replaces any existing Graph with the same URI) /// </summary> /// <param name="g">Graph to save</param> /// <remarks> /// <para> /// Completely replaces any existing Graph with the same Uri in the store /// </para> /// <para> /// Attempting to save a Graph which doesn't have a Base Uri will result in an error /// </para> /// </remarks> /// <exception cref="RdfStorageException">Thrown if you try and save a Graph without a Base Uri or if there is an error communicating with the 4store instance</exception> public void SaveGraph(IGraph g) { try { // Set up the Request HttpWebRequest request; if (g.BaseUri != null) { request = (HttpWebRequest)WebRequest.Create(_baseUri + "data/" + Uri.EscapeUriString(g.BaseUri.AbsoluteUri)); } else { throw new RdfStorageException("Cannot save a Graph without a Base URI to a 4store Server"); } request.Method = "PUT"; request.ContentType = MimeTypesHelper.Turtle[0]; request = ApplyRequestOptions(request); // Write the Graph as Turtle to the Request Stream CompressingTurtleWriter writer = new CompressingTurtleWriter(WriterCompressionLevel.High); writer.Save(g, new StreamWriter(request.GetRequestStream())); Tools.HttpDebugRequest(request); // Make the Request using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Tools.HttpDebugResponse(response); // If we get here then it was OK response.Close(); } } catch (WebException webEx) { throw StorageHelper.HandleHttpError(webEx, "saving a Graph to"); } }