/// <summary> /// Writes the SPARQL Result Set to a String and returns the Output in your chosen format /// </summary> /// <param name="results">SPARQL Result Set</param> /// <param name="writer">Writer to use to generate the SPARQL Results output</param> /// <returns></returns> public static String Write(SparqlResultSet results, ISparqlResultsWriter writer) { System.IO.StringWriter sw = new System.IO.StringWriter(); writer.Save(results, sw); return(sw.ToString()); }
public static void Save(this ISparqlResultsWriter resultsWriter, SparqlResultSet resultSet, string filename) { using (var output = new StreamWriter(filename)) { resultsWriter.Save(resultSet, output); } }
/// <summary> /// Creates a new GZipped Results writer /// </summary> /// <param name="writer">Underlying writer</param> public BaseGZipResultsWriter(ISparqlResultsWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } this._writer = writer; this._writer.Warning += this.RaiseWarning; }
private void EnsureTestData(String file, ISparqlResultsWriter writer) { if (!File.Exists(file)) { Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); SparqlResultSet results = g.ExecuteQuery("SELECT * WHERE { ?s ?p ?o }") as SparqlResultSet; if (results == null) Assert.Fail("Failed to generate sample SPARQL Results"); writer.Save(results, file); } }
private bool SetResultsFormat(String format) { switch (format) { case "xml": this._resultsWriter = new SparqlXmlWriter(); this._graphWriter = new RdfXmlWriter(); break; case "json": this._resultsWriter = new SparqlJsonWriter(); this._graphWriter = new RdfJsonWriter(); break; case "ntriples": this._graphWriter = new NTriplesWriter(); break; case "rdfxml": this._graphWriter = new RdfXmlWriter(); break; case "turtle": this._graphWriter = new CompressingTurtleWriter(WriterCompressionLevel.High); break; case "n3": this._graphWriter = new Notation3Writer(WriterCompressionLevel.High); break; case "html": case "rdfa": this._resultsWriter = new SparqlHtmlWriter(); this._graphWriter = new HtmlWriter(); break; case "csv": this._resultsWriter = new SparqlCsvWriter(); this._graphWriter = new CsvWriter(); break; case "tsv": this._resultsWriter = new SparqlTsvWriter(); this._graphWriter = new TsvWriter(); break; default: Console.Error.WriteLine("rdfQuery: The value '" + format + "' is not a valid Results Format"); return(false); } return(true); }
private void TestSparqlWriterConneg(String header, Type expected, String contentType) { String ctype; ISparqlResultsWriter writer = MimeTypesHelper.GetSparqlWriter(header, out ctype); Console.WriteLine("Accept Header: " + header); Console.WriteLine("Expected Writer: " + expected.Name); Console.WriteLine("Actual Writer: " + writer.GetType().Name); Console.WriteLine("Expected Content Type: " + contentType); Console.WriteLine("Actual Content Type: " + ctype); Assert.AreEqual(expected, writer.GetType()); Assert.AreEqual(contentType, ctype); }
private void EnsureTestData(String file, ISparqlResultsWriter writer) { if (!File.Exists(file)) { Graph g = new Graph(); g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); g.Retract(g.Triples.Where(t => !t.IsGroundTriple).ToList()); SparqlResultSet results = g.ExecuteQuery("SELECT * WHERE { ?s ?p ?o }") as SparqlResultSet; if (results == null) { Assert.True(false, "Failed to generate sample SPARQL Results"); } writer.Save(results, file); } }
private void btnExport_Click(object sender, EventArgs e) { ExportResultSetOptionsForm exporter = new ExportResultSetOptionsForm(); if (exporter.ShowDialog() == DialogResult.OK) { ISparqlResultsWriter writer = exporter.Writer; String file = exporter.File; try { writer.Save(this._results, file); MessageBox.Show("Successfully exported the SPARQL Results to the file '" + file + "'", "SPARQL Results Export Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("An error occurred attempting to export the SPARQL Results:\n" + ex.Message, "SPARQL Results Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/// <summary> /// Creates a new Export SPARQL Results Options Form /// </summary> public ExportResultSetOptionsForm() { InitializeComponent(); //Load Writers Type targetType = typeof(ISparqlResultsWriter); List <ISparqlResultsWriter> writers = new List <ISparqlResultsWriter>(); foreach (Type t in Assembly.GetAssembly(targetType).GetTypes()) { if (t.Namespace == null) { continue; } if (t.Namespace.Equals("VDS.RDF.Writing")) { if (t.GetInterfaces().Contains(targetType)) { try { ISparqlResultsWriter writer = (ISparqlResultsWriter)Activator.CreateInstance(t); writers.Add(writer); } catch { //Ignore this Writer } } } } writers.Sort(new ToStringComparer <ISparqlResultsWriter>()); this.cboWriter.DataSource = writers; if (this.cboWriter.Items.Count > 0) { this.cboWriter.SelectedIndex = 0; } this.cboWriter.SelectedIndex = 0; }
private void cboResultsFormat_SelectedIndexChanged(object sender, EventArgs e) { fclsStylesheetPicker stylesheetPicker; switch (this.cboResultsFormat.SelectedIndex) { case 0: this._resultswriter = new SparqlCsvWriter(); this._resultsext = ".csv"; break; case 1: this._resultswriter = new SparqlRdfWriter(this._rdfwriter); this._resultsext = this._rdfext; break; case 2: this._resultswriter = new SparqlHtmlWriter(); this._resultsext = ".html"; break; case 3: stylesheetPicker = new fclsStylesheetPicker("CSS"); if (stylesheetPicker.ShowDialog() == DialogResult.OK) { SparqlHtmlWriter temp = new SparqlHtmlWriter(); temp.Stylesheet = stylesheetPicker.StylesheetUri; this._resultswriter = temp; } else { this._resultswriter = new SparqlHtmlWriter(); } this._resultsext = ".html"; break; case 4: this._resultswriter = new SparqlJsonWriter(); this._resultsext = ".json"; break; case 5: this._resultswriter = new SparqlTsvWriter(); this._resultsext = ".tsv"; break; case 6: this._resultswriter = new SparqlXmlWriter(); this._resultsext = ".srx"; break; case 7: stylesheetPicker = new fclsStylesheetPicker("XSLT"); if (stylesheetPicker.ShowDialog() == DialogResult.OK) { try { this._resultswriter = new SparqlXsltWriter(stylesheetPicker.StylesheetUri); this._resultsext = ".xml"; } catch (Exception ex) { MessageBox.Show("Unable to use the selected XSLT Stylesheet due to the following error:\n" + ex.Message, "Invalid Stylesheet", MessageBoxButtons.OK, MessageBoxIcon.Warning); this.cboResultsFormat.SelectedIndex = 2; this._resultswriter = new SparqlHtmlWriter(); this._resultsext = ".html"; } } else { this.cboResultsFormat.SelectedIndex = 2; this._resultswriter = new SparqlHtmlWriter(); this._resultsext = ".html"; } break; } }
/// <summary> /// Creates a new GZipped Results writer /// </summary> /// <param name="writer">Underlying writer</param> public BaseGZipResultsWriter(ISparqlResultsWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); this._writer = writer; this._writer.Warning += this.RaiseWarning; }
/// <summary> /// Registers a writer as the default SPARQL Results Writer for all the given MIME types and updates relevant definitions to include the MIME types and file extensions /// </summary> /// <param name="writer">SPARQL Results Writer</param> /// <param name="mimeTypes">MIME Types</param> /// <param name="fileExtensions">File Extensions</param> public static void RegisterWriter(ISparqlResultsWriter writer, IEnumerable<String> mimeTypes, IEnumerable<String> fileExtensions) { if (!_init) Init(); if (!mimeTypes.Any()) throw new RdfException("Cannot register a writer without specifying at least 1 MIME Type"); //Get any existing defintions that are to be altered IEnumerable<MimeTypeDefinition> existing = GetDefinitions(mimeTypes); foreach (MimeTypeDefinition def in existing) { foreach (String type in mimeTypes) { def.AddMimeType(type); } foreach (String ext in fileExtensions) { def.AddFileExtension(ext); } def.SparqlResultsWriterType = writer.GetType(); } //Create any new defintions IEnumerable<String> newTypes = mimeTypes.Where(t => !GetDefinitions(t).Any()); if (newTypes.Any()) { MimeTypeDefinition newDef = new MimeTypeDefinition(String.Empty, newTypes, fileExtensions); newDef.SparqlResultsWriterType = writer.GetType(); AddDefinition(newDef); } }
private void cboGraphFormat_SelectedIndexChanged(object sender, EventArgs e) { switch (this.cboGraphFormat.SelectedIndex) { case 0: this._rdfwriter = new CsvWriter(); this._rdfext = ".csv"; break; case 1: fclsStylesheetPicker stylesheetPicker = new fclsStylesheetPicker("CSS (Optional)"); if (stylesheetPicker.ShowDialog() == DialogResult.OK) { HtmlWriter temp = new HtmlWriter(); temp.Stylesheet = stylesheetPicker.StylesheetUri; this._rdfwriter = temp; } else { this._rdfwriter = new HtmlWriter(); } this._rdfext = ".html"; break; case 2: this._rdfwriter = new Notation3Writer(); this._rdfext = ".n3"; break; case 3: this._rdfwriter = new NTriplesWriter(); this._rdfext = ".nt"; break; case 4: this._rdfwriter = new RdfJsonWriter(); this._rdfext = ".json"; break; case 5: this._rdfwriter = new RdfXmlWriter(); this._rdfext = ".rdf"; break; case 6: this._rdfwriter = new CompressingTurtleWriter(); this._rdfext = ".ttl"; break; case 7: this._rdfwriter = new TsvWriter(); this._rdfext = ".tsv"; break; } if (this._rdfwriter is ICompressingWriter) { ((ICompressingWriter)this._rdfwriter).CompressionLevel = WriterCompressionLevel.High; } if (this.cboResultsFormat.SelectedIndex == 1) { this._resultswriter = new SparqlRdfWriter(this._rdfwriter); this._resultsext = this._rdfext; } }
// See https://github.com/dotnetrdf/dotnetrdf/blob/5b7fc480346c90eb9b164fb4f8ee09f378442d52/Libraries/dotNetRDF.Web/HandlerHelper.cs#L157 /// <summary> /// Helper function which returns the Results (Graph/Triple Store/SPARQL Results) back to the Client in one of their accepted formats /// </summary> /// <param name="context">Context of the HTTP Request</param> /// <param name="result">Results of the Sparql Query</param> /// <param name="config">Handler Configuration</param> public static void SendToClient(HttpContext context, SparqlQueryResult result) { MimeTypeDefinition definition = null; const string TEXT_PLAIN = "text/plain"; var acceptTypes = context.Request.Headers[HeaderNames.Accept]; // Return the Results if (result.SparqlResultSet != null) { ISparqlResultsWriter sparqlWriter = null; // Try and get a MIME Type Definition using the HTTP Requests Accept Header if (acceptTypes.Count > 0) { definition = MimeTypesHelper.GetDefinitions((IEnumerable <string>)acceptTypes).FirstOrDefault(d => d.CanWriteSparqlResults); } // Try and get the registered Definition for SPARQL Results XML if (definition == null) { definition = MimeTypesHelper.GetDefinitions(MimeTypesHelper.SparqlResultsXml[0]).FirstOrDefault(); } // If Definition is still null create a temporary definition if (definition == null) { definition = new MimeTypeDefinition("SPARQL Results XML", MimeTypesHelper.SparqlResultsXml, Enumerable.Empty <String>()); definition.SparqlResultsWriterType = typeof(VDS.RDF.Writing.SparqlXmlWriter); } // Set up the Writer appropriately sparqlWriter = definition.GetSparqlResultsWriter(); context.Response.ContentType = definition.CanonicalMimeType; // HandlerHelper.ApplyWriterOptions(sparqlWriter, config); // Send Result Set to Client context.Response.Headers[HeaderNames.ContentEncoding] = definition.Encoding.WebName; sparqlWriter.Save(result.SparqlResultSet, new StreamWriter(context.Response.Body, definition.Encoding)); } else if (result.Graph != null) { IRdfWriter rdfWriter = null; var ctype = TEXT_PLAIN; // Try and get a MIME Type Definition using the HTTP Requests Accept Header if (acceptTypes.Count > 0) { definition = MimeTypesHelper.GetDefinitions((IEnumerable <string>)acceptTypes).FirstOrDefault(d => d.CanWriteRdf); } if (definition == null) { // If no appropriate definition then use the GetWriter method instead rdfWriter = MimeTypesHelper.GetWriter((IEnumerable <string>)acceptTypes, out ctype); } else { rdfWriter = definition.GetRdfWriter(); } // Setup the writer if (definition != null) { ctype = definition.CanonicalMimeType; } context.Response.ContentType = ctype; //HandlerHelper.ApplyWriterOptions(rdfWriter, config); // Clear any existing Response //context.Response.Clear(); // Send Graph to Client if (definition != null) { context.Response.Headers[HeaderNames.ContentEncoding] = definition.Encoding.WebName; rdfWriter.Save(result.Graph, new StreamWriter(context.Response.Body, definition.Encoding)); } else { rdfWriter.Save(result.Graph, new StreamWriter(context.Response.Body)); } } else { Debug.Assert(result == SparqlQueryResult.Null); } }
private void EnsureTestData(String file) { ISparqlResultsWriter writer = MimeTypesHelper.GetSparqlWriter(MimeTypesHelper.GetMimeTypes(Path.GetExtension(file))); this.EnsureTestData(file, writer); }
/// <summary> /// Helper function which returns the Results (Graph/Triple Store/SPARQL Results) back to the Client in one of their accepted formats /// </summary> /// <param name="context">Context of the HTTP Request</param> /// <param name="result">Results of the Sparql Query</param> /// <param name="config">Handler Configuration</param> public static void SendToClient(HttpContext context, Object result, BaseHandlerConfiguration config) { MimeTypeDefinition definition = null; String ctype = "text/plain"; String[] acceptTypes = HandlerHelper.GetAcceptTypes(context); //Return the Results if (result is SparqlResultSet) { ISparqlResultsWriter sparqlWriter = null; //Try and get a MIME Type Definition using the HTTP Requests Accept Header if (acceptTypes != null) { definition = MimeTypesHelper.GetDefinitions(acceptTypes).FirstOrDefault(d => d.CanWriteSparqlResults); } //Try and get the registered Definition for SPARQL Results XML if (definition == null) { definition = MimeTypesHelper.GetDefinitions(MimeTypesHelper.SparqlXml[0]).FirstOrDefault(); } //If Definition is still null create a temporary definition if (definition == null) { definition = new MimeTypeDefinition("SPARQL Results XML", MimeTypesHelper.SparqlXml, Enumerable.Empty <String>()); definition.SparqlResultsWriterType = typeof(VDS.RDF.Writing.SparqlXmlWriter); } //Set up the Writer appropriately sparqlWriter = definition.GetSparqlResultsWriter(); context.Response.ContentType = definition.CanonicalMimeType; HandlerHelper.ApplyWriterOptions(sparqlWriter, config); //Clear any existing Response context.Response.Clear(); //Send Result Set to Client context.Response.ContentEncoding = definition.Encoding; sparqlWriter.Save((SparqlResultSet)result, new StreamWriter(context.Response.OutputStream, definition.Encoding)); } else if (result is IGraph) { IRdfWriter rdfWriter = null; //Try and get a MIME Type Definition using the HTTP Requests Accept Header if (acceptTypes != null) { definition = MimeTypesHelper.GetDefinitions(acceptTypes).FirstOrDefault(d => d.CanWriteRdf); } if (definition == null) { //If no appropriate definition then use the GetWriter method instead rdfWriter = MimeTypesHelper.GetWriter(acceptTypes, out ctype); } else { rdfWriter = definition.GetRdfWriter(); } //Setup the writer if (definition != null) { ctype = definition.CanonicalMimeType; } context.Response.ContentType = ctype; HandlerHelper.ApplyWriterOptions(rdfWriter, config); //Clear any existing Response context.Response.Clear(); //Send Graph to Client if (definition != null) { context.Response.ContentEncoding = definition.Encoding; rdfWriter.Save((IGraph)result, new StreamWriter(context.Response.OutputStream, definition.Encoding)); } else { rdfWriter.Save((IGraph)result, new StreamWriter(context.Response.OutputStream)); } } else if (result is ITripleStore) { IStoreWriter storeWriter = null; //Try and get a MIME Type Definition using the HTTP Requests Accept Header if (acceptTypes != null) { definition = MimeTypesHelper.GetDefinitions(acceptTypes).FirstOrDefault(d => d.CanWriteRdfDatasets); } if (definition == null) { //If no appropriate definition then use the GetStoreWriter method instead storeWriter = MimeTypesHelper.GetStoreWriter(acceptTypes, out ctype); } else { storeWriter = definition.GetRdfDatasetWriter(); } //Setup the writer if (definition != null) { ctype = definition.CanonicalMimeType; } context.Response.ContentType = ctype; HandlerHelper.ApplyWriterOptions(storeWriter, config); //Clear any existing Response context.Response.Clear(); //Send Triple Store to Client if (definition != null) { context.Response.ContentEncoding = definition.Encoding; storeWriter.Save((ITripleStore)result, new VDS.RDF.Storage.Params.StreamParams(context.Response.OutputStream, definition.Encoding)); } else { storeWriter.Save((ITripleStore)result, new VDS.RDF.Storage.Params.StreamParams(context.Response.OutputStream)); } } else if (result is ISparqlDataset) { //Wrap in a Triple Store and then call self so the Triple Store writing branch of this if gets called instead TripleStore store = new TripleStore(new DatasetGraphCollection((ISparqlDataset)result)); HandlerHelper.SendToClient(context, store, config); } else { throw new RdfOutputException("Unexpected Result Object of Type '" + result.GetType().ToString() + "' returned - unable to write Objects of this Type to the HTTP Response"); } }
static void DoQuery(Dictionary <String, String> arguments) { SparqlRemoteEndpoint endpoint; bool verbose = arguments.ContainsKey("verbose") || arguments.ContainsKey("v"); if (verbose) { Options.HttpDebugging = true; } //First get the Server to which we are going to connect try { if (arguments.ContainsKey("server") && !arguments["server"].Equals(String.Empty)) { endpoint = new SparqlRemoteEndpoint(new Uri(arguments["server"])); } else if (arguments.ContainsKey("service") && !arguments["service"].Equals(String.Empty)) { endpoint = new SparqlRemoteEndpoint(new Uri(arguments["service"])); } else { Console.Error.WriteLine("soh: Error: Required --server/--service argument not present"); Environment.Exit(-1); return; } } catch (UriFormatException uriEx) { Console.Error.WriteLine("soh: Error: Malformed SPARQL Endpoint URI"); Console.Error.WriteLine(uriEx.Message); Environment.Exit(-1); return; } if (verbose) { Console.Error.WriteLine("soh: SPARQL Endpoint for URI " + endpoint.Uri + " created OK"); } //Then decide where to get the query to execute from SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery query; try { if (arguments.ContainsKey("query") && !arguments["query"].Equals(String.Empty)) { query = parser.ParseFromFile(arguments["query"]); } else if (arguments.ContainsKey("file") && !arguments["file"].Equals(String.Empty)) { query = parser.ParseFromFile(arguments["file"]); } else if (arguments.ContainsKey("$1") && !arguments["$1"].Equals(String.Empty)) { query = parser.ParseFromString(arguments["$1"]); } else { Console.Error.WriteLine("soh: Error: Required SPARQL Query not found - may be specified as --file/--query FILE or as final argument"); Environment.Exit(-1); return; } } catch (Exception ex) { Console.Error.WriteLine("soh: Error: Error Parsing SPARQL Query"); Console.Error.WriteLine(ex.Message); Environment.Exit(-1); return; } if (verbose) { Console.Error.WriteLine("soh: Parsed Query OK"); Console.Error.WriteLine("soh: dotNetRDF's interpretation of the Query:"); SparqlFormatter formatter = new SparqlFormatter(); Console.Error.WriteLine(formatter.Format(query)); Console.Error.WriteLine("soh: Submitting Query"); } try { using (HttpWebResponse response = endpoint.QueryRaw(query.ToString())) { MimeTypeDefinition definition = MimeTypesHelper.GetDefinitions(response.ContentType).FirstOrDefault(); Encoding enc; if (definition != null) { enc = definition.Encoding; } else if (!response.ContentEncoding.Equals(String.Empty)) { enc = Encoding.GetEncoding(response.ContentEncoding); } else if (response.ContentType.Contains("charset=")) { enc = Encoding.GetEncoding(response.ContentType.Substring(response.ContentType.IndexOf('=') + 1)); } else { enc = Console.OutputEncoding; } if (verbose) { Console.Error.WriteLine("soh: Got Response from SPARQL Endpoint OK"); Console.Error.WriteLine("soh: Content-Type: " + response.ContentType); Console.Error.WriteLine("soh: Content-Encoding: " + enc.WebName); } String requestedType = arguments.ContainsKey("accept") ? arguments["accept"] : null; if (requestedType == null || response.ContentType.StartsWith(requestedType, StringComparison.OrdinalIgnoreCase)) { //If no --accept (OR matches servers content type) then just return whatever the server has given us using (StreamReader reader = new StreamReader(response.GetResponseStream())) { using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(), enc)) { while (!reader.EndOfStream) { writer.WriteLine(reader.ReadLine()); } writer.Close(); } reader.Close(); } } else { if (verbose) { Console.Error.WriteLine("soh: Warning: Retrieved Content Type '" + response.ContentType + "' does not match your desired Content Type '" + requestedType + "' so dotNetRDF will not attempt to transcode the response into your desired format"); } //Requested Type Doesn't match servers returned type so parse then serialize MimeTypeDefinition outputDefinition; try { ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType); SparqlResultSet results = new SparqlResultSet(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { sparqlParser.Load(results, reader); reader.Close(); } outputDefinition = MimeTypesHelper.GetDefinitions(requestedType).FirstOrDefault(d => d.CanWriteSparqlResults || d.CanWriteRdf); if (outputDefinition == null) { throw new RdfWriterSelectionException("No MIME Type Definition for the MIME Type '" + requestedType + "' was found that can write SPARQL Results/RDF"); } ISparqlResultsWriter writer = outputDefinition.GetSparqlResultsWriter(); Console.OutputEncoding = outputDefinition.Encoding; writer.Save(results, new StreamWriter(Console.OpenStandardOutput(), outputDefinition.Encoding)); } catch (RdfParserSelectionException) { try { IRdfReader rdfParser = MimeTypesHelper.GetParser(response.ContentType); Graph g = new Graph(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { rdfParser.Load(g, reader); reader.Close(); } outputDefinition = MimeTypesHelper.GetDefinitions(requestedType).FirstOrDefault(d => d.CanWriteRdf); if (outputDefinition == null) { throw new RdfWriterSelectionException("No MIME Type Definition for the MIME Type '" + requestedType + "' was found that can write RDF"); } IRdfWriter writer = outputDefinition.GetRdfWriter(); Console.OutputEncoding = outputDefinition.Encoding; writer.Save(g, new StreamWriter(Console.OpenStandardOutput(), outputDefinition.Encoding)); } catch (Exception ex) { //For any other exception show a warning Console.Error.WriteLine("soh: Warning: You wanted results in the format '" + requestedType + "' but the server returned '" + response.ContentType + "' and dotNetRDF was unable to translate the response into your desired format."); Console.Error.WriteLine(ex.Message); } } catch (Exception ex) { //For any other exception show a warning Console.Error.WriteLine("soh: Warning: You wanted results in the format '" + requestedType + "' but the server returned '" + response.ContentType + "' and dotNetRDF was unable to translate the response into your desired format."); Console.Error.WriteLine(ex.Message); } } response.Close(); } if (verbose) { Console.Error.WriteLine("soh: Query Completed OK"); } } catch (Exception ex) { Console.Error.WriteLine("soh: Error: Error while making the SPARQL Query"); Console.Error.WriteLine(ex.Message); Environment.Exit(-1); return; } }
public BrightstarSparqlResultsType ExecuteSparql(SparqlQuery query, IStore store, TextWriter resultsWriter) { try { EnsureValidResultFormat(query); var dataset = MakeDataset(store); if (_defaultGraphUris != null) { dataset.SetDefaultGraph(_defaultGraphUris); } var queryProcessor = new BrightstarQueryProcessor(store, dataset); var queryResult = queryProcessor.ProcessQuery(query); if (queryResult is SparqlResultSet) { var sparqlResultSet = (SparqlResultSet)queryResult; ISparqlResultsWriter sparqlResultsWriter = null; if (_sparqlResultsFormat != null) { sparqlResultsWriter = MimeTypesHelper.GetSparqlWriter(new string[] { _sparqlResultsFormat.ToString() }); } if (sparqlResultsWriter == null) { throw new NoAcceptableFormatException(typeof(SparqlResultsFormat), "No acceptable format provided for writing a SPARQL result set."); } sparqlResultsWriter.Save(sparqlResultSet, resultsWriter); switch (sparqlResultSet.ResultsType) { case SparqlResultsType.Boolean: return(BrightstarSparqlResultsType.Boolean); case SparqlResultsType.VariableBindings: return(BrightstarSparqlResultsType.VariableBindings); default: throw new BrightstarInternalException("Unrecognized SPARQL result type"); } } if (queryResult is IGraph) { var g = (IGraph)queryResult; var rdfWriter = _rdfFormat == null ? null : MimeTypesHelper.GetWriter(new string[] { _rdfFormat.ToString() }); if (rdfWriter == null) { throw new NoAcceptableFormatException(typeof(RdfFormat), "No acceptable format provided for writing an RDF graph result."); } rdfWriter.Save(g, resultsWriter); try { resultsWriter.Flush(); } catch (ObjectDisposedException) { // resultWriter is already closed } return(BrightstarSparqlResultsType.Graph); } throw new BrightstarInternalException( String.Format("Unexpected return type from QueryProcessor.ProcessQuery: {0}", queryResult.GetType())); } catch (Exception ex) { Logging.LogError(BrightstarEventId.SparqlExecutionError, "Error Executing query {0}. Cause: {1}", query.ToString(), ex); throw; } }
private bool SetOptions(String[] args) { if (args.Length == 0 || args.Length == 1 && args[0].Equals("-help")) { this.ShowUsage(); return(false); } String arg; int i = 0; while (i < args.Length) { arg = args[i]; if (arg.StartsWith("-uri:")) { if (this._mode == RdfQueryMode.Remote) { Console.Error.WriteLine("rdfQuery: Cannot specify input URIs as well as specifying a remote endpoint to query"); return(false); } String uri = arg.Substring(5); try { this._mode = RdfQueryMode.Local; //Try and parse RDF from the given URI if (!this._print) { Uri u = new Uri(uri); Graph g = new Graph(); UriLoader.Load(g, u); this._store.Add(g); } else { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since -print has been specified so the query will not be executed so no need to load the data"); } } catch (UriFormatException uriEx) { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since this is not a valid URI"); if (this._debug) { this.DebugErrors(uriEx); } } catch (RdfParseException parseEx) { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message); if (this._debug) { this.DebugErrors(parseEx); } } catch (Exception ex) { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Error: " + ex.Message); if (this._debug) { this.DebugErrors(ex); } } } else if (arg.StartsWith("-endpoint:")) { if (this._mode == RdfQueryMode.Local) { Console.Error.WriteLine("rdfQuery: Cannot specify a remote endpoint to query as well as specifying local files and/or input URIs"); return(false); } else if (this._mode == RdfQueryMode.Remote) { if (!(this._endpoint is FederatedSparqlRemoteEndpoint)) { this._endpoint = new FederatedSparqlRemoteEndpoint(this._endpoint); } } try { this._mode = RdfQueryMode.Remote; if (this._endpoint is FederatedSparqlRemoteEndpoint) { ((FederatedSparqlRemoteEndpoint)this._endpoint).AddEndpoint(new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1)))); } else { this._endpoint = new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1))); } } catch (UriFormatException uriEx) { Console.Error.WriteLine("rdfQuery: Unable to use remote endpoint with URI '" + arg.Substring(arg.IndexOf(':') + 1) + "' since this is not a valid URI"); if (this._debug) { this.DebugErrors(uriEx); } return(false); } } else if (arg.StartsWith("-output:") || arg.StartsWith("-out:")) { this._output = arg.Substring(arg.IndexOf(':') + 1); } else if (arg.StartsWith("-outformat:")) { String format = arg.Substring(arg.IndexOf(':') + 1); try { if (format.Contains("/")) { //MIME Type this._graphWriter = MimeTypesHelper.GetWriter(format); this._resultsWriter = MimeTypesHelper.GetSparqlWriter(format); } else { //File Extension this._graphWriter = MimeTypesHelper.GetWriterByFileExtension(format); this._resultsWriter = MimeTypesHelper.GetSparqlWriterByFileExtension(format); } } catch (RdfException) { Console.Error.WriteLine("rdfQuery: The file extension '" + format + "' could not be used to determine a MIME Type and select a writer - default writers will be used"); } } else if (arg.StartsWith("-syntax")) { if (arg.Contains(':')) { String syntax = arg.Substring(arg.IndexOf(':') + 1); switch (syntax) { case "1": case "1.0": this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_0; break; case "1.1": this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_1; break; case "E": case "e": this._parser.SyntaxMode = SparqlQuerySyntax.Extended; break; default: Console.Error.WriteLine("rdfQuery: The value '" + syntax + "' is not a valid query syntax specifier - assuming SPARQL 1.1 with Extensions"); this._parser.SyntaxMode = SparqlQuerySyntax.Extended; break; } } else { this._parser.SyntaxMode = SparqlQuerySyntax.Extended; } } else if (arg.StartsWith("-timeout:")) { long timeout; if (Int64.TryParse(arg.Substring(arg.IndexOf(':') + 1), out timeout)) { this._timeout = timeout; } else { Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid timeout in milliseconds - default timeouts will be used"); } } else if (arg.StartsWith("-r:")) { arg = arg.Substring(arg.IndexOf(':') + 1); switch (arg) { case "rdfs": ((IInferencingTripleStore)this._store).AddInferenceEngine(new RdfsReasoner()); break; case "skos": ((IInferencingTripleStore)this._store).AddInferenceEngine(new SkosReasoner()); break; default: Console.Error.WriteLine("rdfQuery: The value '" + arg + "' is not a valid Reasoner - ignoring this option"); break; } } else if (arg.StartsWith("-partialResults")) { if (arg.Contains(':')) { bool partial; if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out partial)) { this._partialResults = partial; } else { Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid boolean - partial results mode is disabled"); } } else { this._partialResults = true; } } else if (arg.StartsWith("-noopt")) { if (arg.Equals("-noopt")) { Options.QueryOptimisation = false; Options.AlgebraOptimisation = false; } else if (arg.Length >= 7) { String opts = arg.Substring(7); foreach (char c in opts.ToCharArray()) { if (c == 'a' || c == 'A') { Options.AlgebraOptimisation = false; } else if (c == 'q' || c == 'Q') { Options.QueryOptimisation = false; } else { Console.Error.WriteLine("rdfQuery: The value '" + c + "' as part of the -noopt argument is not supported - it has been ignored"); } } } } else if (arg.Equals("-nocache")) { Options.UriLoaderCaching = false; } else if (arg.Equals("-nobom")) { Options.UseBomForUtf8 = false; } else if (arg.Equals("-print")) { this._print = true; } else if (arg.Equals("-debug")) { this._debug = true; } else if (arg.StartsWith("-explain")) { this._explain = true; if (arg.Length > 9) { try { this._level = (ExplanationLevel)Enum.Parse(typeof(ExplanationLevel), arg.Substring(9)); this._level = (this._level | ExplanationLevel.OutputToConsoleStdErr | ExplanationLevel.Simulate) ^ ExplanationLevel.OutputToConsoleStdOut; } catch { Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' does not specify a valid Explanation Level"); return(false); } } } else if (arg.Equals("-help")) { //Ignore Help Argument if other arguments present } else if (arg.StartsWith("-")) { //Report Invalid Argument Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' is not a supported argument - it has been ignored"); } else if (i == args.Length - 1) { //Last Argument must be the Query this._query = arg; } else { //Treat as an input file if (this._mode == RdfQueryMode.Remote) { Console.Error.WriteLine("rdfQuery: Cannot specify local files as well as specifying a remote endpoint to query"); return(false); } try { this._mode = RdfQueryMode.Local; //Try and parse RDF from the given file if (!this._print) { Graph g = new Graph(); FileLoader.Load(g, arg); this._store.Add(g); } else { Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' since -print has been specified so the query will not be executed so no need to load the data"); } } catch (RdfParseException parseEx) { Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message); if (this._debug) { this.DebugErrors(parseEx); } } catch (Exception ex) { Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Error: " + ex.Message); if (this._debug) { this.DebugErrors(ex); } } } i++; } return(true); }
public void Setup() { this._g = new Graph(); this._g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl"); this._results = this._g.ExecuteQuery("SELECT * WHERE { ?s ?p ?o }") as SparqlResultSet; foreach (MimeTypeDefinition def in MimeTypesHelper.Definitions) { // Omit CSV since that is a lossy format that does not round trip if (def.CanonicalMimeType.Equals("text/csv")) { continue; } if (def.CanWriteRdf && def.CanParseRdf) { IRdfWriter writer = def.GetRdfWriter(); bool isManual = !def.CanonicalFileExtension.EndsWith(".gz"); String filename = "gzip-tests" + (isManual ? String.Empty : "-auto") + "." + def.CanonicalFileExtension + (isManual ? ".gz" : String.Empty); if (isManual) { using (StreamWriter output = new StreamWriter(new GZipStream(new FileStream(filename, FileMode.Create, FileAccess.Write), CompressionMode.Compress))) { writer.Save(this._g, output); output.Close(); } this._manualTestFiles.Add(filename); } else { writer.Save(this._g, filename); this._autoTestFiles.Add(filename); } } else if (def.CanParseRdfDatasets && def.CanWriteRdfDatasets) { IStoreWriter writer = def.GetRdfDatasetWriter(); bool isManual = !def.CanonicalFileExtension.EndsWith(".gz"); String filename = "gzip-tests-datasets" + (isManual ? String.Empty : "-auto") + "." + def.CanonicalFileExtension + (isManual ? ".gz" : String.Empty); TripleStore store = new TripleStore(); store.Add(this._g); if (isManual) { using (Stream output = new GZipStream(new FileStream(filename, FileMode.Create, FileAccess.Write), CompressionMode.Compress)) { writer.Save(store, new StreamWriter(output)); output.Close(); } this._manualDatasetTestFiles.Add(filename); } else { writer.Save(store, new StreamWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); this._autoDatasetTestFiles.Add(filename); } } else if (def.CanParseSparqlResults && def.CanWriteSparqlResults) { ISparqlResultsWriter writer = def.GetSparqlResultsWriter(); bool isManual = !def.CanonicalFileExtension.EndsWith(".gz"); String filename = "gzip-tests-results" + (isManual ? String.Empty : "-auto") + "." + def.CanonicalFileExtension + (isManual ? ".gz" : String.Empty); if (isManual) { using (StreamWriter output = new StreamWriter(new GZipStream(new FileStream(filename, FileMode.Create, FileAccess.Write), CompressionMode.Compress))) { writer.Save(this._results, output); output.Close(); } this._manualResultsTestFiles.Add(filename); } else { writer.Save(this._results, new StreamWriter(filename)); this._autoResultsTestFiles.Add(filename); } } } }
private bool SetOptions(String[] args) { if (args.Length == 0 || args.Length == 1 && args[0].Equals("-help")) { this.ShowUsage(); return false; } String arg; int i = 0; while (i < args.Length) { arg = args[i]; if (arg.StartsWith("-uri:")) { if (this._mode == RdfQueryMode.Remote) { Console.Error.WriteLine("rdfQuery: Cannot specify input URIs as well as specifying a remote endpoint to query"); return false; } String uri = arg.Substring(5); try { this._mode = RdfQueryMode.Local; //Try and parse RDF from the given URI if (!this._print) { Uri u = new Uri(uri); Graph g = new Graph(); UriLoader.Load(g, u); this._store.Add(g); } else { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since -print has been specified so the query will not be executed so no need to load the data"); } } catch (UriFormatException uriEx) { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since this is not a valid URI"); if (this._debug) this.DebugErrors(uriEx); } catch (RdfParseException parseEx) { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message); if (this._debug) this.DebugErrors(parseEx); } catch (Exception ex) { Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Error: " + ex.Message); if (this._debug) this.DebugErrors(ex); } } else if (arg.StartsWith("-endpoint:")) { if (this._mode == RdfQueryMode.Local) { Console.Error.WriteLine("rdfQuery: Cannot specify a remote endpoint to query as well as specifying local files and/or input URIs"); return false; } else if (this._mode == RdfQueryMode.Remote) { if (!(this._endpoint is FederatedSparqlRemoteEndpoint)) { this._endpoint = new FederatedSparqlRemoteEndpoint(this._endpoint); } } try { this._mode = RdfQueryMode.Remote; if (this._endpoint is FederatedSparqlRemoteEndpoint) { ((FederatedSparqlRemoteEndpoint)this._endpoint).AddEndpoint(new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1)))); } else { this._endpoint = new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1))); } } catch (UriFormatException uriEx) { Console.Error.WriteLine("rdfQuery: Unable to use remote endpoint with URI '" + arg.Substring(arg.IndexOf(':') + 1) + "' since this is not a valid URI"); if (this._debug) this.DebugErrors(uriEx); return false; } } else if (arg.StartsWith("-output:") || arg.StartsWith("-out:")) { this._output = arg.Substring(arg.IndexOf(':') + 1); } else if (arg.StartsWith("-outformat:")) { String format = arg.Substring(arg.IndexOf(':') + 1); try { if (format.Contains("/")) { //MIME Type this._graphWriter = MimeTypesHelper.GetWriter(format); this._resultsWriter = MimeTypesHelper.GetSparqlWriter(format); } else { //File Extension this._graphWriter = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(format)); this._resultsWriter = MimeTypesHelper.GetSparqlWriter(MimeTypesHelper.GetMimeType(format)); } } catch (RdfException) { Console.Error.WriteLine("rdfQuery: The file extension '" + format + "' could not be used to determine a MIME Type and select a writer - default writers will be used"); } } else if (arg.StartsWith("-syntax")) { if (arg.Contains(':')) { String syntax = arg.Substring(arg.IndexOf(':') + 1); switch (syntax) { case "1": case "1.0": this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_0; break; case "1.1": this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_1; break; case "E": case "e": this._parser.SyntaxMode = SparqlQuerySyntax.Extended; break; default: Console.Error.WriteLine("rdfQuery: The value '" + syntax + "' is not a valid query syntax specifier - assuming SPARQL 1.1 with Extensions"); this._parser.SyntaxMode = SparqlQuerySyntax.Extended; break; } } else { this._parser.SyntaxMode = SparqlQuerySyntax.Extended; } } else if (arg.StartsWith("-timeout:")) { long timeout; if (Int64.TryParse(arg.Substring(arg.IndexOf(':') + 1), out timeout)) { this._timeout = timeout; } else { Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid timeout in milliseconds - default timeouts will be used"); } } else if (arg.StartsWith("-r:")) { arg = arg.Substring(arg.IndexOf(':') + 1); switch (arg) { case "rdfs": ((IInferencingTripleStore)this._store).AddInferenceEngine(new RdfsReasoner()); break; case "skos": ((IInferencingTripleStore)this._store).AddInferenceEngine(new SkosReasoner()); break; default: Console.Error.WriteLine("rdfQuery: The value '" + arg + "' is not a valid Reasoner - ignoring this option"); break; } } else if (arg.StartsWith("-partialResults")) { if (arg.Contains(':')) { bool partial; if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out partial)) { this._partialResults = partial; } else { Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid boolean - partial results mode is disabled"); } } else { this._partialResults = true; } } else if (arg.StartsWith("-noopt")) { if (arg.Equals("-noopt")) { Options.QueryOptimisation = false; Options.AlgebraOptimisation = false; } else if (arg.Length >= 7) { String opts = arg.Substring(7); foreach (char c in opts.ToCharArray()) { if (c == 'a' || c == 'A') { Options.AlgebraOptimisation = false; } else if (c == 'q' || c == 'Q') { Options.QueryOptimisation = false; } else { Console.Error.WriteLine("rdfQuery: The value '" + c + "' as part of the -noopt argument is not supported - it has been ignored"); } } } } else if (arg.Equals("-nocache")) { Options.UriLoaderCaching = false; } else if (arg.Equals("-nobom")) { Options.UseBomForUtf8 = false; } else if (arg.Equals("-print")) { this._print = true; } else if (arg.Equals("-debug")) { this._debug = true; } else if (arg.StartsWith("-explain")) { this._explain = true; if (arg.Length > 9) { try { this._level = (ExplanationLevel)Enum.Parse(typeof(ExplanationLevel), arg.Substring(9)); this._level = (this._level | ExplanationLevel.OutputToConsoleStdErr | ExplanationLevel.Simulate) ^ ExplanationLevel.OutputToConsoleStdOut; } catch { Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' does not specify a valid Explanation Level"); return false; } } } else if (arg.Equals("-help")) { //Ignore Help Argument if other arguments present } else if (arg.StartsWith("-")) { //Report Invalid Argument Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' is not a supported argument - it has been ignored"); } else if (i == args.Length - 1) { //Last Argument must be the Query this._query = arg; } else { //Treat as an input file if (this._mode == RdfQueryMode.Remote) { Console.Error.WriteLine("rdfQuery: Cannot specify local files as well as specifying a remote endpoint to query"); return false; } try { this._mode = RdfQueryMode.Local; //Try and parse RDF from the given file if (!this._print) { Graph g = new Graph(); FileLoader.Load(g, arg); this._store.Add(g); } else { Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' since -print has been specified so the query will not be executed so no need to load the data"); } } catch (RdfParseException parseEx) { Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message); if (this._debug) this.DebugErrors(parseEx); } catch (Exception ex) { Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:"); Console.Error.WriteLine("rdfQuery: Error: " + ex.Message); if (this._debug) this.DebugErrors(ex); } } i++; } return true; }
/// <summary> /// Writes the SPARQL Result Set to a String and returns the Output in your chosen format /// </summary> /// <param name="results">SPARQL Result Set</param> /// <param name="writer">Writer to use to generate the SPARQL Results output</param> /// <returns></returns> public static String Write(SparqlResultSet results, ISparqlResultsWriter writer) { System.IO.StringWriter sw = new System.IO.StringWriter(); writer.Save(results, sw); return sw.ToString(); }
private bool SetResultsFormat(String format) { switch (format) { case "xml": this._resultsWriter = new SparqlXmlWriter(); this._graphWriter = new FastRdfXmlWriter(); break; case "json": this._resultsWriter = new SparqlJsonWriter(); this._graphWriter = new RdfJsonWriter(); break; case "ntriples": this._graphWriter = new NTriplesWriter(); break; case "rdfxml": this._graphWriter = new FastRdfXmlWriter(); break; case "turtle": this._graphWriter = new CompressingTurtleWriter(WriterCompressionLevel.High); break; case "n3": this._graphWriter = new Notation3Writer(WriterCompressionLevel.High); break; case "html": case "rdfa": this._resultsWriter = new SparqlHtmlWriter(); this._graphWriter = new HtmlWriter(); break; case "csv": this._resultsWriter = new SparqlCsvWriter(); this._graphWriter = new CsvWriter(); break; case "tsv": this._resultsWriter = new SparqlTsvWriter(); this._graphWriter = new TsvWriter(); break; default: Console.Error.WriteLine("rdfQuery: The value '" + format + "' is not a valid Results Format"); return false; } return true; }